Suppose *ptr
points to a variable. What does *ptr
, &ptr
, and ptr
each mean?
Many times, I get confused between them. Do anyone mind clarifying between those statements and give some concrete examples?
Take the following variables in a function.
int i = 0;
int* ptr = &i;
In the function, the memory layout could look something like:
Memory corresponding to i
:
+---+---+---+---+
| 0 |
+---+---+---+---+
^
|
Address of i
Memory corresponding to ptr
:
+---+---+---+---+
| address of i |
+---+---+---+---+
^
|
Address of ptr
In the above scenario,
*ptr == i == 0
ptr == address of i == address of memory location where the vale of i is stored
&ptr == address of ptr == address of memory location where the value of ptr is stored.
Hope that makes sense.
Here is a computer memory:
int i = 1023
If I want to print i
, then I just have to do:
printf(..., i);
// out: 1023
If I want to print where i
lives, then I just have to do:
printf(..., &i);
// out: 0x4
But let's say I want to remember where i
lives:
int *i_ptr = &i; // i_ptr is a variable of type int *
Then I can print it this way:
printf(..., i_ptr);
// out: 0x04
But if just print out the value of i
, I need a *
:
printf(..., *i_ptr); // * also doubles as a way to follow the pointer
// out: 1023
Or I can just print out where i_ptr
lives:
printf(..., &i_ptr);
// out: 0x32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With