Reputation: 2058
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?
Upvotes: 3
Views: 337
Reputation: 91017
The first string
is an array. Its address points to this array:
+-+-+-+-+-+-+-+-+-+-+-+
|s|o|m|e| |s|t|r|i|n|g|
+-+-+-+-+-+-+-+-+-+-+-+
The address of this array is a pointer to, well, an array, so a *char[]
.
The second string
is a pointer pointing to the same string which lies (probably, but depending on the implementation) in read only space:
+------+ +-+-+-+-+-+-+-+-+-+-+-+
| addr | -> |s|o|m|e| |s|t|r|i|n|g|
+------+ +-+-+-+-+-+-+-+-+-+-+-+
The address of this pointer is a **char
.
Upvotes: 0
Reputation: 7448
Actually if I can add to Timothy's answer, the char (*ptr)[12] = &string;
type of pointer is fairly unusual as it is a pointer to an array of particular type and size.
Let's see what happens when we print its address before and after we've incremented it by one:
char string[] = "some string";
char (*ptr)[12] = &string;
printf("Before: %p\n", (void*)(ptr));
printf("After: %p\n", (void*)(ptr+1));
Which prints:
Before: 0xbfec44e0
After: 0xbfec44ec
Notice how in the second case the pointer has been moved 12 blocks of memory. Since the pointer knows the size of the type it points to this applies in the case of an array as well, not just for any plain old type. Which in our case is 12.
There's an indepth explanation of this here, that you migh want to read.
Upvotes: 0
Reputation: 22125
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
arr
is an array, what's the difference betweenarr
and&arr
?A: In Standard C,
&arr
yields 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);
Upvotes: 9
Reputation: 2625
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);
Upvotes: 4