What does *p mean when **p is already declared?
short **p = (short **)malloc(sizeof(short *));
(better written as)
short **p = malloc (sizeof *p);
Declares the pointer-to-pointer-to short
p
and allocates storage for a signle pointer with malloc
and assigns the beginning address for that block of memory to p
. See: In C, there is no need to cast the return of malloc
, it is unnecessary. See: Do I cast the result of malloc?
*p = malloc(sizeof(short));
(equivalent to)
p[0] = malloc (sizeof *p[0]);
Allocates storage for a single short
and assigns the starting address for that block of memory to p[0]
.
**p = 10;
(equivalent to)
*p[0] = 10;
(or)
p[0][0] = 10;
Assigns the value 10
to the dereference pointer *p[0]
(or **p
or p[0][0]
) updating the value at that memory address to 10
.
printf("**p = %d", **p);
Prints the value stored in the block of memory pointed to by p[0]
(the value accessed by dereferencing the pointer as *p[0]
or **p
)
The way to keep this straight in your head, is p
is a single pointer of type pointer-to-pointer-to short
. There are 2-level of indirection (e.g. pointer-to-pointer). To remove one level of indirection, you use the unary *
operator, e.g.
*p /* has type pointer-to short */
or the [..]
also acts as a dereference such that:
p[0] /* also has type pointer-to short */
You still have a pointer-to so you must remove one more level of indirection to refernce the value stored at the memory location pointed to by the pointer. (e.g. the pointer holds the address where the short
is stored as its value). So you need:
**p /* has type short */
and
*p[0] /* also has type short */
as would
p[0][0] /* also has type short */
The other piece to keep straight is the type controls pointer-arithmetic. So p++
adds 8-bytes to the pointer-to-ponter address so it now points to the next pointer. If you do short *q = (*p)++;
(or short *q = p[0]++, adds 2-bytes to the address for the pointer-to-short, so
qnow points to the next
shortin the block of memory beginning at
*p(or
p[0]`). (there is no 2nd short because you only allocated 1 -- but you get the point)
Let me know if you have further questions.