4

I am just trying to understand the pointers concept in C and came across this error. I got the "lvalue required as increment operand" error for the following code. Please help me understand what is wrong.

#include<stdio.h>

int main()
{
    char *s[] = {"black", "white", "pink", "violet"};
    ++s; //error at this line
    printf("%s\n", *s);
    char **ptr[] = {s+3, s+2, s+1, s}, ***p;
    p = ptr;
    ++p;
    printf("%s", **p+1);
    return 0;
}
Tcl_newbie
  • 135
  • 1
  • 4
  • 14

2 Answers2

1

s is an array of pointers to char. Array names are non-modifiable l-value. ++s is modifying s which can't be modified.

Array Names vs Pointer Variables:

As we have seen, when we declare an array, a contiguous block of memory is allocated for the cells of the array and a pointer cell (of the appropriate type) is also allocated and initialized to point to the first cell of the array. This pointer cell is given the name of the array. When memory is allocated for the array cells, the starting address is fixed, i.e. it cannot be changed during program execution. Therefore, the value of the pointer cell should not be changed. To ensure that this pointer is not changed, in C, array names may not be used as variables on the left of an assignment statement, i.e. they may not be used as an Lvalue. Instead, if necessary, separate pointer variables of the appropriate type may be declared and used as Lvalues.


Suggested reading: Is array name a pointer in C?

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
1

The problem is that in expressions an array name is converted to an rvalue of pointer to the first element of the array. That is a temporary object of type in your case char ** is created. You may not increment a temporary object. The situation is similar to what occur in the following code snippet

int x = 10;

++( x + 5 );

The compiler will issue a similar error message.

For example in your code snippet you may not write

char **ptr[] = { ++(s+3), s+2, s+1, s};

The compiler will issue the same error. In fact when you write ++s then it is equivalent to ++( s + 0 ) that is you deal not with the original array but with some temporary pointer that is rvalue`

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335