5

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?

3
  • 1
    Very interesting! My guess is that it considers char *argv[] equivalent to char **argv but not so with a user-defined pointer to array.. Commented Oct 19, 2015 at 0:48
  • 7
    A local variable char *array[] is an array of pointers. A function argument char *argv[] is actually a char **argv. C11 draft standard 6.7.6.3 Function declarators (including prototypes), Section 7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’[...]. Commented Oct 19, 2015 at 0:49
  • 2
    char *argv[] passed to main() decays to char **, not so with your direct use of *array[] in main() Commented Oct 19, 2015 at 0:50

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.