Reputation: 35
I am new to C and now I am trying to learn the basics of linked list. The following code is only the segment of traversing a linked list.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int item;
struct node *next;
};
int main()
{
struct node *start,*list;
int i;
start = (struct node *)malloc(sizeof(struct node));
list = start;
start->next = NULL;
for(i=0;i<10;i++)
{
list->item = i;
printf("%p\t%p\n",start->next,list->next);
list->next = (struct node *)malloc(sizeof(struct node));
list = list->next;
}
return 0;
}
I am confused that the output of "start->next" is not NULL, but a solid constant address. But I assigned NULL to start->next before the for loop, and only change the component in "list" (list->item and list->next), not the component in "start". So why component in "start" is changed?
Upvotes: 0
Views: 254
Reputation: 16553
Remember that you have: list = start
: They then both point to the same node, and as long as they are equal, list->next
is the same as start->next
.
On the for
first iteration start
and list
are still equal and start->next
will be NULL until you assign: list->next = ...
.
After that first assignment, start->next
will be modified to point at the malloced address.
On the next iterations list
is pointing to other places and modifying list->next
doesn't affect start->next
.
Step by step: ("node X" are the names I give to the nodes allocated by malloc, they are not variables in your program)
node 0: { .item = ?, .next = NULL } <---- start, list
i = 0;
list->item = i;
node 0: { .item = 0, .next = NULL } <---- start, list
list->next = malloc(...)
node 0: { .item = 0, .next = &(node 1) } <---- start, list
node 1: { .item = ?, .next = ? } <---- start->next, list->next
list = list->next
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = ?, .next = ? } <---- start->next, list
i = 1;
list->item = i;
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = 1, .next = ? } <---- start->next, list
list->next = malloc(...)
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = 1, .next = &(node 2) } <---- start->next, list
node 2: { .item = ?, .next = ? } <---- list->next
list = list->next;
node 0: { .item = 0, .next = &(node 1) } <---- start
node 1: { .item = 1, .next = &(node 2) } <---- start->next
node 2: { .item = ?, .next = ? } <---- list
etc.
Upvotes: 4
Reputation: 16607
This is because if this assignment-
list = start;
list
points to same address to which start
points to, so changes made at that location are same to both pointers (as they point to same memory location).
It is same as this example (maybe more simple as code)-
int a;
int *p1,*p2;
p1=&a;
p2=p1;
*p1=5;
prinf("value : p1=%d p2=%d",*p1, *p2 );
/* Both the pointer will have same value as change is made at memory location */
Upvotes: 2