user3663685
user3663685

Reputation: 63

Different pointer address printed inside function

I am new to C and pointers. The following is some code that i was experimenting with.

struct node{
    struct node * next;
    struct node * prev;
    int num;
 };

 void func(struct node * leaf , struct node ** add_leaf){
     printf("function starts");
     printf("&leaf = %p  add_leaf = %p\n" , &leaf , add_leaf);
     printf("leaf = %p  *add_leaf = %p\n" , leaf , *add_leaf);
     printf("function over");
     return
 }


 void main(){
     struct node * leaf = (struct node*)malloc(sizeof(struct node));
     printf("leaf = %p\t&leaf = %p\n" , leaf , &leaf);
     func(leaf , &leaf);
 }

The values of leaf and *add_leaf are equal and that was what i expected. However I could not understand why was there a difference in the values of &leaf and add_leaf when printed inside the function. Here, I am trying to print the address of the node pointer leaf.

Upvotes: 5

Views: 212

Answers (3)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

I usually find it easier to understand pointers if you draw a picture with arrows and boxes.

&leaf gives you the address of the varible leaf, and since you have two different variables named leaf (both containing pointers to your malloc-allocated struct), you get two different addresses:

enter image description here

Upvotes: 2

sampathsris
sampathsris

Reputation: 22270

leaf is a pointer to a struct node, and a pointer is a 32 bit (depending on architecture) integer that is stored somewhere in memory.

When you pass leaf to printf, what happens is, a copy of the leaf variable will be made on the stack. That copy corresponds to the 2nd local argument of printf function.

But when you pass &leaf to the printf function, what you do is you pass the address of the leaf variable.

Since the leaf variable in main() and the 2nd argument of printf are in two different locations, it will indeed print two memory addresses.

Upvotes: 0

Alexander Gessler
Alexander Gessler

Reputation: 46607

The local variable leaf in the main is copied when func is invoked. This means, the local variable leaf inside func has the same value as leaf inside main, i.e. it points to the same memory address (thus equivalence for the second check), but it is itself stored at a different address.

Upvotes: 3

Related Questions