Reputation: 1
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, therefore 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?
Upvotes: 0
Views: 1247
Reputation: 35154
Variables are passed by value; this is also true for a variable whose value is a pointer:
Suppose variable head
of type struct node*
points to a node, let's say a node at address 0x12345
.
When you call printList(head)
, whereas the signature of this function is void printList(struct node *n)
, then the value of head
is copied to the value of n
; Hence, variable n
and variable head
, though being different variables, will have the value 0x12345
. If printList
then changes the value of n
, e.g. by statement n = n->next
, then only the value of variable n
is changed; variable head
will still have the value 0x12345
.
Hope this helps...
Upvotes: 1
Reputation: 44256
C passes parameters by value. That means that the value of the variable passed to a function is copied into a new variable which is local to the function. No matter how much you change the local variable inside the function, it will never change the value of the variable passed to the function.
In other words: n
inside the function is not the same as head
in main
. The local variable n
is just initialized to the same value as head
Upvotes: 2