Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lvalue required error

Tags:

c

pointers

While working with pointers i wrote the following code,

int main()
{
    int a[]={10,20,30,40,50};
    int i;
    for(i=0;i<5;i++)
    {
        printf("\n%d",*a);
        a++;
    }
    return 0;
}

Now as per my understanding array name itself is an address in c and the pointer arithmetic done is here is correct as per my knowledge. But when i try to run the code it is giving me "Lvalue Required" error.

So what is the exact reason for occuring Lvalue required error because before this also i have come across situations where this error is there. Secondly why the arithmetic on the pointer is not legal here in this case?

like image 694
Ankur Trapasiya Avatar asked Nov 21 '11 21:11

Ankur Trapasiya


1 Answers

You can't do a++ on a static array - which is not an Lvalue. You need to do on a pointer instead. Try this:

int *ptr = a;
int i;
for(i=0;i<5;i++)
{
    printf("\n%d",*ptr);
    ptr++;
}

Although in this case, it's probably better to just use the index:

int i;
for(i=0;i<5;i++)
{
    printf("\n%d",a[i]);
}
like image 179
Mysticial Avatar answered Sep 23 '22 20:09

Mysticial