Home > Blockchain >  In C, given char *ptr and defined till ptr n, when I tried statements similar to (ptr i) = (ptr j);
In C, given char *ptr and defined till ptr n, when I tried statements similar to (ptr i) = (ptr j);

Time:10-25

While compiling this below given code, I got the error: lvalue required as left operand of assignment for both the statements str i = str ((len-1)-i); and str ((len-1)-i) = temp;.

Why?

char* str_reverse(char *str, int len)
{
    char *temp;
    int i, mid;

    if(len%2 == 0)
    {
        mid = len/2 - 1;
    }
    else
    {
        mid = (len-1)/2;
    }

    for(i=0;i<mid;i  )
    {
        temp = str i;
        str i = str ((len-1)-i);
        str ((len-1)-i) = temp;
    }

    return str;
}

CodePudding user response:

str is an lvalue because it is a place in memory which contains an address.

str i is only an rvalue because it is only an address

CodePudding user response:

Use size_t for string lengths.

You are overcomplicating this:

char* str_reverse(char *str, size_t len)
{
    char temp, *start = str, *end = str   len -1;
    if(str && *str)
    {
        while(start < end)
        {
            temp = *start;
            *start   = *end;
            *end-- = temp;
        }
    }
    return str;
}

CodePudding user response:

Expressions like this

str   i

are rvalues. They can not be assigned. It is the same as to write

int x = 10;
int y = 20;

x   y = 30;

But in any case your function is in essence incorrect. You need to swap characters instead of trying to swap pointer expressions.

Also this if statement

if(len%2 == 0)
{
    mid = len/2 - 1;
}
else
{
    mid = (len-1)/2;
}

does not make a great sense because the result of the expression

len / 2

is the same whether len is an even number or the following odd number.

For example 2 / 2 is equal to 1 and 3 / 2 is also equal to 1.

Using pointers within the function it can be defined the following way

char * str_reverse( char *str, size_t len )
{
    if ( len != 0 )
    {
        for ( char *left = str, *right = str   len; left < --right;   left )
        {
            char c = *left;
            *left = *right;
            *right = c;
        }
    }

    return str;
}
  • Related