1

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!

Community
  • 1
  • 1
me_digvijay
  • 5,374
  • 9
  • 46
  • 83

5 Answers5

5

arr is a constant, you can't change its value. You can add a

int *p = arr;

And then do a

p++;
Bart
  • 19,692
  • 7
  • 68
  • 77
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • 2
    You should explain here that "arr" isn't merely a constant -- it is an array, not a pointer. Although C makes arrays and pointers look similar, they are not the same sort of thing -- you cannot increment an array. – Perry Feb 27 '12 at 17:47
3

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);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

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.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
1

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".

Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
1

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
John Bode
  • 119,563
  • 19
  • 122
  • 198