lvalue required as increment operand

gcc 4.4.4

What am I doing wrong?

char x[10];
char y[] = "Hello";
while(y != NULL)
    *x++ = *y++;

Many thanks for any advice.


x++ is the short form of x = x + 1. However, x here is an array and you cannot modify the address of an array. So is the case with your variable y too.

Instead of trying to increment arrays, you can declare an integer i and increment that, then access the i'th index of an arrays.

char x[10], y[5] = "Hello";
int i = 0;
while (y[i] != 0)
{
    x[i] = *y[i];
    i++;
}
x[i] = 0;

Most likely you fell victim to a popular misconception that "array is a pointer", i.e. when you define an array what you actually get is an ordinary pointer that points to some block of memory allocated somewhere. In your code you are making an attempt to increment that pointer.

The code does not "work" because in reality arrays are not pointers. Arrays are arrays. Arrays cannot be incremented. There's no such operation as "increment an array" in C language. In fact, arrays by themselves in C are non-modifiable lvalues. There are no operations in C that can modify the array itself (only individual elements can be modifiable).

If you want to traverse your arrays using the "sliding pointer" technique (which is what you are actually trying to do), you need to create the pointers explicitly and make them point to the starting elements of your arrays

char *px = x;
char *py = y;

After that you can increment these pointers as much as you want.


Arrays in C are indeed pointers, but constant pointers, which means after declaration their values can't be changed.

int arr[] = {1, 2, 3};
// arr is declared as const pointer.

(arr + 1) is possible but arr++ is not possible because arr can not store another address since it is constant.


char x[10];
char y[] = "Hello";
char *p_x = &x[0];
char *p_y = &y[0];
while(*p_y != '\0') *p_x++ = *p_y++;

Since you can't modify the array addresses (done by x++ and y++ in your code) and you can modify the pointer address, I copied over the address of the array into separate pointers and then incremented them.

If you want, I'm sure you can reduce the notation, but I hope you got the point.