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