Incrementing an array of pointers in C

this is probably an almost trivial thing, but so far it has eluded me somewhat.

char * a3[2];
a3[0] = "abc";
a3[1] = "def";
char ** p;
p = a3;

it works:

printf("%p - \"%s\"\n", p, *(++p));

this is not true:

printf("%p - \"%s\"\n", a3, *(++a3));

The error I get when compiling:

lvalue required as an increment operand

what am I doing wrong, why and what is the solution for "a3"?

+6
source share
5 answers

a3 is a constant pointer, you cannot increase it. "p" however is a common pointer to the start of a3, which can be increased.

+4
source

You cannot assign a3 , nor can you increase it. The name of the array is a constant; it cannot be changed.

c-faq

+4
source

Try

 char *a3Ptr = a3; printf("%p - \"%s\"\n", a3, *(++a3Ptr)); 

In C, the char [] array is different from char *, even if you can use char * to refer to the first location of the char array.

aren't the p and a3 pointers pointers?

Yes, but a3 is constant. You cannot change it.

0
source

a3 is the name of the array. This is about him as a constant pointer.

You cannot change it. You can use a3 + 1 instead of ++a3 .

Another problem is to use " %s " for the argument *(++a3) . Since a3 is an array of char, *a3 is a character, and the corresponding format specifier should be %c .

0
source

You cannot increment or point any char array to anything else after creation. You need to modify or access using the index. like a[1]

0
source

Source: https://habr.com/ru/post/889686/


All Articles