Program:
int x;
int *y;
int **z;
z = (int **) malloc (sizeof(int *));
y = (int *) malloc (sizeof(int));
x = 1;
*z = &x;
*y = x;
.
.
.
Question: What is the difference between:
*z = &x;
*y = x;
From what I understand *z points to the address of x and *y points to x, but for *y to point to x doesn't that require the address of x? I don't really understand what's going on with these two variables.
Edit: I also want to know when do we know when a variable is allocated on the stack or on the heap?
Finally, does changing *z, change **z?
z
is a pointer to a pointer (which will typically point to a dynamically allocated array of pointers).
y
is a pointer to int
. Again, more often than not it'll point to a dynamically allocated array of int
s.
So, the *z = &x;
is setting the pointer that z
refers to to point at x
. I.e., z
points at a pointer, which (in turn) points to x
.
*y = x;
is taking the value of x
and assigning it to the int
pointed to by y
.
For things like this, a picture is often helpful. So, our basic definitions give us this:
The we do:
z = (int **) malloc (sizeof(int *));
y = (int *) malloc (sizeof(int));
Which gives us this:
Then we do:
*z = &x;
*y = x;
Which gives us this:
In all of these, a dashed line signifies a pointer from one place to another, while the solid line indicates copying a value from one place to another.
We can then consider the long-term differences between them. For example, consider what happens if we add x=2;
after all the assignments above.
In this case, *y
will still equal 1
, because we copied the value 1
from x
to *y
. **z
will equal 2
though, because it's just a pointer to x
-- any change in x
will be reflected in **z
.
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