Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with increment operator in pointer array?

Tags:

arrays

c

pointers

I just found a little confusion while using increment operator in pointer array.

Code 1:

int main(void) {
     char *array[] = {"howdy", "mani"};
     printf("%s", *(++array));
     return 0;
}

While compiling, gcc throws a well known error "lvalue required as increment operand".

But, when I compile the below code it shows no error!!! Why?

Code2:

int main(int argc, char *argv[]) {
     printf("%s",*(++argv));
     return 0;
}

In both cases, I have been incrementing an array of pointer. So, it should be done by this way.

char *array[] = {"howdy","mani"};
char **pointer = array;
printf("%s",*(++pointer));

But, why code2 shows no error?

like image 616
Mani Sadhasivam Avatar asked Oct 19 '15 00:10

Mani Sadhasivam


People also ask

Why can't we increment an array like a pointer?

It's because array is treated as a constant pointer in the function it is declared.

Can I increment array pointer?

Pointers are also useful while working with arrays, because we can use the pointer instead of an index of the array. A pointer can be incremented by value or by address based on the pointer data type.

What happens when you increment an array?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

Can we increment array address?

Array memory addresses remain constant, so you cannot change it.


1 Answers

Arrays cannot be incremented.

In your first code sample you try to increment an array. In the second code sample you try to increment a pointer.

What's tripping you up is that when an array declarator appears in a function parameter list, it actually gets adjusted to be a pointer declarator. (This is different to array-pointer decay). In the second snippet, char *argv[] actually means char **argv.

See this thread for a similar discussion.

like image 147
M.M Avatar answered Oct 21 '22 15:10

M.M