Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different pointer address printed inside function

Tags:

c

pointers

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.

like image 932
user3663685 Avatar asked Jul 13 '14 13:07

user3663685


1 Answers

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.

like image 173
Alexander Gessler Avatar answered Oct 01 '22 04:10

Alexander Gessler