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.
The pre-increment operator requires an L-value as operand, hence the compiler throws an error. The increment/decrement operators needs to update the operand after the sequence point, so they need an L-value. The unary operators such as -, +, won't need L-value as operand. The expression -(++i) is valid.
lvalue required as left operand of assignment. lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear). Both function results and constants are not assignable ( rvalue s), so they are rvalue s.
The "l" stands for "left", as in the left hand side of the equals sign. An rvalue is the right hand value and produces a value, and cannot be assigned to directly. If you are getting "lvalue required" you have an expression that produces an rvalue when an lvalue is required.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With