0

Suppose that I have an array of pointers:

char *names[] = { "Za" , "John"};

Can I declare it like this:(?)

char **names = { "Za" , "John" }    

The reason I am trying to do this is that I am trying to increment the array to print its contents such that I can do:

printf("%s \n" , *(++names))

So I can get printf to print "John".

I tried the declaration char **names and I got the following warning upon compilation:

test.c: In function ‘main’:
test.c:6:2: warning: initialization from incompatible pointer type [enabled by default]
  char **names = { "Za" , "John"};
  ^
test.c:6:2: warning: (near initialization for ‘names’) [enabled by default]
test.c:6:2: warning: excess elements in scalar initializer [enabled by default]
test.c:6:2: warning: (near initialization for ‘names’) [enabled by default]

P.S my C file name is test.c

Thanks.

2
  • 1
    You do know that a pointer to a pointer to char is not and can never be the same as an array of pointers to char. Commented Mar 15, 2014 at 22:48
  • @JoachimPileborg Thanks for the insight, from what I said what would tell you that I don't? I am really trying to figure this out... A pointer to a pointer to char , is an address of another address of a character, while an array of pointers to char is an array of addresses of characters. Do I make sense? Commented Mar 15, 2014 at 22:58

1 Answer 1

2

Just do char **pCurrentName = names;, then you'll be able to do printf("%s \n" , *(++pCurrentName)).

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

9 Comments

Thanks it works but I am really interested in the reasoning of why this works, and why what I did doesn't work.
@kolonel You should see a pointer variable as what it is, but an array used in pointer context rather as a value of an appropriate pointer. So you can use it for assignments, but you cannot assign it anything.
@glglgl thanks for commenting, but could you provide more details of what you think is wrong with my logic?
That initializer is invalid for names. You must get a compiler error if you try it. But if you provided a valid initializer, names could be incremented.
To elaborate, { x, y } can only be the initializer for an array with at least two elements. But you are trying to initialize a pointer. It's not possible for the initializer to create an anonymous array and then the pointer points to the first element of that array. It is the same problem as this line has, char const *c = { 'a', 'b', '\0' };.
|

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.