Linked List in C++

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



In other words, after calling printList(head), it is reasonable to me that the pointer head must now point to a null value
No. That would be the case if printList() was written like this, for example:
1
2
3
4
5
6
7
8
9
void printList2(struct node **n){
    while (*n != NULL){
        printf(" %d ", (*n)->data);
        *n = (*n)->next;
    }
}

//Usage:
printList2(&head);
printList() receives and modifies a copy of the 'head' pointer. The original pointer, held by main(), remains unchanged.
1) Please use code tags when posting code, to make it readable:

http://www.cplusplus.com/articles/z13hAqkS/

2) You're passing the pointer into the function by value, which means that the pointer inside the function is a copy of the one in the calling code. Any changes you make to the value of the pointer will not be reflected in the value of the pointer in the calling code.

Remember, a pointer is just a variable, like any other, and it behaves like any other variable.

Do not confuse the value of the pointer, with the value of the thing that it is pointing to.
Thank you very much, that was very helpful.
You're welcome - glad it helped!
Topic archived. No new replies allowed.