An Address Written Down
An address is a number. You can store a number. If you store an address, you need a variable to put it in. That variable is a pointer. That is the entire definition, and people write whole books about it.
int x = 42;
int *p = &x;Look at the second line. p is a variable. It has its own house on the street, same as anything else. The value inside p is the address of x. A pointer is a variable whose value is an address. Say it twice. Done.
Now the asterisk, which is the one that got me. & asks where does this live. * says go there and bring me what you find. One asks, one goes. That is the whole relationship.
printf("%d\n", *p); // 42, the int at the address p is holding
*p = 7; // write 7 into that house
printf("%d\n", x); // 7. x changed. *p and x are the same four bytesThat last line is where it clicked for me. *p is not a copy of x. It is x. Same house, different road to get there. Two names, one set of bytes.
The declaration confused me for years, so here is how I read it now, and it is the only way to read it. int *p does not say “p is a pointer to an int.” It says “*p is an int.” It is a promise about what you get when you follow the arrow. Read it that way and the declaration and the use are the same sentence. Very elegant. Nobody explains it like that.
| Expression | Reads as | Is a… |
|---|---|---|
x | the value | int |
&x | where x lives | address of an int |
p | the address I wrote down | address of an int |
*p | the int at that address | int, the same one as x |
Two operators. One asks where, one goes there. Everything else in this book is those two questions asked in new places. Believe me.