If I write:
char string[] = "some string";
char **ptr = &string;
printf("%s\n",*ptr);
It prints nothing and gives a warning: warning: initialization from incompatible pointer type [enabled by default]
Now, if I write the following:
char *string = "another string";
char **ptr = &string;
printf("%s\n",*ptr);
It works all right.
Shouldn't string[] decay to a pointer similar to *string and work? Why doesn't it?
That's not how the decay works in in this case. See the C faq:
6.12 Q: Since array references decay into pointers, if
arris an array, what's the difference betweenarrand&arr?A: In Standard C,
&arryields a pointer, of type pointer-to-array-of-T, to the entire array.
So, when you do:
char string[] = "some string";
char **ptr = &string;
The assignment fails, because &string is of type "pointer to char array of length 12". You could instead write:
char (*ptr)[12] = &string;
Which (while almost certainly not what you're trying to do) reads "declare ptr as a pointer to an array of 12 chars"
If you really want to get a pointer-to-a-pointer, then you could always use an intermediary variable:
char string[] = "some string";
char *ptr = string;
char **doublepointer = &ptr;
printf("%s",*doublepointer);
There's an concept by name pointer to an array.You are using an pointer to point to an array and that's not the way to do it . If you want to point an pointer to an array try the below way you would get the required output .
char string[] = "some string";
char (*ptr)[]=&string;
printf("%s",*ptr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With