Hello there, I have a potentially stupid question. Here is a C code which creates a simple linked list with three nodes. Afterward a function called "printList" traverses the created list and prints the data of each node.
// A simple C program for traversal of a linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
// This function prints contents of linked list starting from
// the given node
void printList(struct node *n)
{
while (n != NULL)
{
printf(" %d ", n->data);
n = n->next;
}
}
int main()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
// allocate 3 nodes in the heap
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
head->data = 1; //assign data in first node
head->next = second; // Link first node with second
second->data = 2; //assign data to second node
second->next = third;
third->data = 3; //assign data to third node
third->next = NULL;
printList(head);
printList(head); //question
return 0;
}
Resource:
http://quiz.geeksforgeeks.org/linked-list-set-1-introduction/
My question is that, since the input argument of function printList is a pointer of type node, the value of the pointer seems to be changed after the function call. In other words, after calling printList(head), it is reasonable to me that the pointer head must now point to a null value, therefor the second call to printList should print some irrelevant values. However, I am obviously wrong, since the output of this program is 1 2 3 1 2 3.
Could you please shed some light on this?
Thanks,
Sherry