0
#include <stdio.h>
#include <string.h>

main()
{
    int x[100];
    int i;
    for(i=0;i<10;i++)
    {
        *(x++) = i;
    }
}

main.c: In function ‘main’: main.c:10:12: error: lvalue required as increment operand *(x++) = i;

Can you please explain why i am getting this error?

user1762571
  • 1,888
  • 7
  • 28
  • 47

4 Answers4

1

A modifiable l-value cannot have an array type. An l-value is an expression which can come on the left side of an assignment. You use an array when you want to declare lots of variables of the same type and you can index it easily since its layout will be in a sense contiguous.

You use pointers when you want to keep changing the values of the address where you variable points to.

What you can do is:

int x[100];
int *p_x = &x[0];
int i;
for(i=0;i<10;i++)
{
    *(p_x++) = i;
}

Since x is an array - its value cannot be modified - when you do x++ you trying to increment its value and hence you get the error.

Sadique
  • 22,572
  • 7
  • 65
  • 91
0

Array names are non-modifiable l-value. You can't modify it. *(++x) = i is wrong. You can try this

int *ptr = x;
for(i=0;i<10;i++)
{
    *(ptr++) = i;
}
haccks
  • 104,019
  • 25
  • 176
  • 264
0

The line:

*(x++) = i

Attempts to increment x, which is the name of the array and is not an lvalue (i.e. cannot appear on the left-hand side of an assignment, and is not modifiable).

Emmet
  • 6,192
  • 26
  • 39
0

Expressions of array type such as x cannot be the operand of the ++ operator.

There's no storage set aside for a variable x apart from the array elements themselves (x[0] through x[99]); IOW, there's nothing in memory to which we can apply the autoincrement operator. x will "decay" to a pointer value in most circumstances, but that pointer value isn't stored anywhere that you can modify it.

As others have shown, you can declare a separate pointer variable and use that instead of x:

int *p = x;
for ( i = 0; i < 100; i++ )
  *p++ = i;

Postfix ++ has higher precedence than unary *, so *p++ will be parsed as *(p++).

Although frankly the following will work just as well:

for ( i = 0; i < 100; i++ )
  x[i] = i;
John Bode
  • 119,563
  • 19
  • 122
  • 198