C programming; lvalue required [duplicate]
Pregunta
Possible Duplicate:
Lvalue required error
I am having an error in my C program
main () {
int arr[] = {1, 2, 3, 4};
printf("%d", *arr);
arr++;
printf("%d", *arr);
}
When I compile this code I get lvalue required error. for the line with arr++. Any Help!
Solución
The operand of the pre- and postfix versions of ++
and --
must be a modifiable lvalue. Unfortunately, array expressions such as arr
are non-modifiable lvalues, hence your error message.
If you want to walk the array using a pointer expression, you'll have to declare a second pointer and set it to point to the first element of the array.
int *p = arr; // or &arr[0] - in this context they evaluate to the same thing
Otros consejos
arr
is a constant, you can't change its value. You can add a
int *p = arr;
And then do a
p++;
Your problem is that arr
is an array and arrays are not lvalues. You need a pointer.
int arr[] = {1, 2, 3, 4};
int *p = &arr;
printf("%d", *p);
p++;
printf("%d", *p);
lvalue
generally refers to the value on the left of an assignment (=) operator. Since arr++
is shorthand for arr = arr + 1
, that's what it's referring to.
Basically, arr as an array, and there is no support for changing the value of an array. I think you want a pointer to the array. Pointers can be incremented in the way your code attempts to.
arr
is constant, you can not change it's value.
Keep it simple, access the array this way:
int main (int argc, char *argv[]) {
int arr[] = {1, 2, 3, 4};
printf("arr[0] == %d\n", arr[0]);
printf("arr[1] == %d\n", arr[1]);
printf("arr[2] == %d\n", arr[2]);
printf("arr[3] == %d", arr[3]);
return 0;
}
I recommend this documentation for lvalues and rvalues.
And also, this c-faq about "Arrays are not pointers".