Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Why pointer to pointer isn't the same thing as pointer to array?

Tags:

arrays

c

pointers

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?

like image 253
2013Asker Avatar asked Feb 26 '26 18:02

2013Asker


2 Answers

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 between arr 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);
like image 90
Timothy Jones Avatar answered Mar 01 '26 10:03

Timothy Jones


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);
like image 27
Santhosh Pai Avatar answered Mar 01 '26 08:03

Santhosh Pai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!