Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers and Memory Allocation in C

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?

  • Why is x,y, and z allocated on the stack?
  • Why is *y, **y, *z, **z, allocated on the heap?

Finally, does changing *z, change **z?

like image 788
Sol Bethany Reaves Avatar asked May 12 '13 14:05

Sol Bethany Reaves


1 Answers

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 ints.

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:

enter image description here

The we do:

z = (int **) malloc (sizeof(int *));
y = (int *) malloc (sizeof(int));

Which gives us this:

enter image description here

Then we do:

*z = &x;
*y = x;

Which gives us this:

enter image description here

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.

like image 90
Jerry Coffin Avatar answered Sep 22 '22 17:09

Jerry Coffin