Search code examples
cpointersreversec-stringsfunction-definition

In C, given char *ptr and defined till ptr+n, when I tried statements similar to (ptr+i) = (ptr+j); where i,j<n, I got "lvalue error". Why?


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;
}

Solution

  • 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;
    }