0
Don’t understand how a pointer works in C
For example: int x = 5; int *p; p = &x; // the two are equivalent to int *p = &x; // Why this one is illegal int **q; *q = &p // but this one works? —> int **q = &p; // Aren’t they the same? Can someone explain it to me? Thank you.
2 Antworten
+ 4
**q is a pointer to an int pointer. It holds an address to an int pointer. All variables will still have their own address in memory. They then also have what they store given their particular type.
Think of the address as a label on a box saying where the box is stored. The type is what should be in the box and the value is what is stored inside the box.
So an int (x) would have its address label on the box and inside the box would be a value of type int. Which is a whole integer number within the types given range.
An int pointer (*p) would still have an address on the box, but the value inside the box would be of type int pointer. An int pointer is itself an address. An address that of another box in memory that holds a value of type int.
The same holds true for a pointer to an int pointer (**q). It has its address on its box and inside its box it holds a value of type pointer to an int pointer. Which again is itself an address to a box that holds an int pointer.
0
Oh, I think i got it. The second one should be
int **q;
q = &p;