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,174
  • 7
  • 43
  • 81

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
  • 18,962
  • 7
  • 68
  • 76
zmbq
  • 36,789
  • 13
  • 91
  • 160
  • 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
  • 587,191
  • 41
  • 1,025
  • 1,442
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
  • 61,921
  • 66
  • 246
  • 419
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,668
  • 5
  • 37
  • 70
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
  • 113,266
  • 18
  • 112
  • 190