Reputation: 143
Why this is possible:
char buf[10], *pbuf = buf, **ppbuf = &pbuf;
and this isn't:
char buf[10], **ppbuf = &buf;
As I understand, the second line is just a shorthand of the first one.
Upvotes: 5
Views: 232
Reputation: 793109
&buf
has the wrong type. &buf
is a pointer to an array of 10 char
. ppbuf
has to be initialized with a pointer to a pointer to a char
.
In the first initialization, while buf
denotes an array, it decays to a char*
pointing to its first element so the initialization is valid.
You also can't do: char buf[10], **ppbuf = &(&buf[0]);
because &buf[0]
is not an lvalue so you can't take its address.
Upvotes: 4
Reputation: 181
It's easy to see it's not the same when you start from:
*pbuf = buf
Since the indirection of pbuf is buf, pbuf contains the address of buf, thus:
pbuf = &buf
So:
**ppbuf != pbuf
**ppbuf != &buf
Upvotes: 1
Reputation: 11522
They're not equivalent.
*pbuf = buf
That means, "pbuf
is a pointer to type char
, whose value is the address of buf
." Since buf
is an array of chars, this works.
**ppbuf = &pbuf
That means, "ppbuf
is a pointer to a pointer to type char
, whose value is the address of pbuf
." Since pbuf
is a pointer to type char
, this works.
**ppbuf = &buf
This means, "ppbuf
is a pointer to a pointer to type char
, whose value is the address of buf
." Since buf
is an array of chars, this fails.
Upvotes: 5
Reputation: 186098
buf is an array, not a pointer, so you can't assign its address to a pointer pointer. pbuf
is a pointer (to the first element of the array), so you can assign its address to a pointer pointer.
Think of the code this way:
typedef char* char_p;
char buf[10];
char_p *ppbuf = &buf; // If this was legal...
*ppbuf = NULL; // what would this mean?
Upvotes: 2