"Error: expression must be a modifiable lvalue" while trying to change char* pointer location

9.4k Views Asked by At

I'm writing a little function in C that eliminates leading whitespace, but it's giving me the "expression must be a modifiable lvalue"

char str1[20];
strcpy (str1, otherStr);

for (int i = 0; i < strlen(str1); i++)
{
    if (!isspace(str1[i]))
        str1 = &(str1[i]);
}

What am I doing wrong here? (And yes, otherStr is defined)

2

There are 2 best solutions below

1
AnT stands with Russia On BEST ANSWER

There's no char * pointer in your code, which one could possibly change. Array is not a pointer. You can't "change" its location.

In C language arrays objects themselves are non-modifiable lvalues, which is where the wording of the error stems from.

0
nategoose On
char *str1 = malloc(20);
// or
// char s[20];
// char * str1 = s; // note the lack &s
// or
// char *str1 = alloca(20);
strcpy (str1, otherStr);

for (int i = 0; i < strlen(str1); i++)
{
    if (!isspace(str1[i]))
        str1 = &(str1[i]);
}

Your code didn't work because when char str1[20] then str1 is not a variable -- for most purposes it is a pointer literal, similar to (void *)0x0342 would be. You can't do 0x0342 = 7; so you can't assign to an array name either.