assuming we have a pointer called
struct node *head
When referring to this as &head
the type becomes pointer to pointer (struct node**) why is this?
assuming we have a pointer called
struct node *head
When referring to this as &head
the type becomes pointer to pointer (struct node**) why is this?
Imagine a real life laser pointer.
You can point it to cars (car *
), to pigeons (pigeon *
), ..., to anything (void *
).
Now use a laser pointer to point to a laser pointer pointing to cars (car **
).
Of course in real life you can point the same laser to a car or a pigeon, etc... but in C that's invalid: a car *
cannot point to pigeons, etc.
You can turn the laser pointer off too (pointer = NULL; /* :-) */
)
Whenever you take the address of something of type T
, the result is of type T*
.
So if the type of head
is struct Node *
, the type of &head
must be of type struct Node **
.
all we are doing is referring to the address of the pointer, which means it's a pointer, right?
They're both pointers, but they're not pointers to the same kind of thing. head
contains a pointer to a Node
structure, but &head
contains a pointer to the variable. "address of the pointer" is not the same as "contents of the pointer", even if the contents are a pointer.
struct node *head;
This means that head
is a pointer to a node
. The contents of head
, then, will be the address of a node
.
Now, consider this:
struct node** p = &head;
The expression &head
evaluates to the address of head
, that is, the address of an object containing the address of a node
. That's why the type of p
is a pointer to a pointer.
Assume the following declaration:
T x; // for some arbitrary type T
The expression x
has type T
, thus the expression &x
1 yields a value of type T *
(pointer to T
). This is true for any type T
.
Now let's replace T
with a pointer type P *
:
P *x; // T -> P *
The expression &x
yields a value of type P **
(T * -> (P *) * == P **
).
So yeah, the expression &head
will yield a value of type struct node **
, and its value will be different from head
.
Multiple indirection shows up a lot in C. It looks weird at first, but you'll get the hang of it soon enough.
[]
or unary *
operator, or an lvalue that designates an object that is not a bit-field and is
not declared with the register
storage-class specifier - C 2011 Online Draft, § 6.5.3.2 Address and indirection operators.