c - why the Push() function in my Linked List implementation shows this behaviour? -
i wrote push() function push element inside linked list. below code, wrote first :
struct node { int data; struct node *next; }; void push(struct node*, int); int main(int argc, char** argv) { struct node *list = null; push(list, 23); return 0; } void push(struct node *list, int data) { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = data; newnode->next = list; list = newnode; }
the code compiles , executes no matter how many numbers push on list, changes doesn't reflect , list remains empty.
then created function other way , used double pointer this:
struct node { int data; struct node *next; }; void push(struct node**, int); int main(int argc, char** argv) { struct node *list = null; push(&list, 23); return 0; } void push(struct node **list, int data) { struct node *newnode; newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = data; newnode->next = *list; *list = newnode; }
here code worked , pushed element on list , change reflected well.
so, why show such different behaviour, though did small test , found both
*list
and
list
contains same address. here did test:
struct node { int data; struct node *next; }; void checkaddress1(struct node *list) { printf("address1 is: %p\n", list); } void checkaddress2(struct node **list) { printf("address3 is: %p\n", *list); } int main(int argc, char** argv) { struct node *list = null; checkaddress1(list); checkaddress2(&list); return 0; }
and output was
address1 is: (nil) address3 is: (nil)
this because both pointing towards same location. means both should work. why different working.can guys elaborate? thanks
list
in main()
has address of first element of list. *list
gives content in memory location pointed list
.
in first program, passing list
push()
value. means list
in push()
merely copy of list
in main()
, modifications made list
of push()
not reflected 1 in main()
.
in second program, passing pointer list
in main()
argument push()
, in push()
manipulate value @ memory location pointed pointer modifying list
in main()
.
hence changes make in push()
reflected main()
program 2 not program 1.
Comments
Post a Comment