Reputation: 539
I have a struct defined as:
typedef struct node Node;
struct node {
char val;
Node* tail;
};
I initiate a linked list like so:
Node* header;
Node node_one;
node_one.val = 'a';
node_one.tail = 0;
header = &node_one;
And then I keep adding nodes to this list. Now when I use the below print function for this linked list, it works the way it is expected to work:
void printlist(Node* header) {
do{
printf("%c ", header->val);
header = header->tail; // aren't we modifying the header itself here?
} while(header->tail!=0);
printf("%c --> NULL", header->val);
}
Called from main()
as printlist(header);
So far so good. What I don't get is, without making any changes to the list, when I call this print function the second, third, fourth time, it always works. It prints the elements of the list. But what I was expecting was that this function would only work once because I am modifying the header pointer itself so shouldn't I lose the list in the memory after running this print function once? How come it works more than once?
Upvotes: 0
Views: 64
Reputation: 355
Probably the header in the function below is a local variable(local to the function printlist). So your original header (header in the main) is not changing at all. So, whenever you call this function it is still printing the list.
void printlist(Node* header){
do{
printf("%c ", header->val);
header = header->tail; // aren't we modifying the header itself here?
}while(header->tail!=0);
printf("%c --> NULL", header->val);
}
Upvotes: 1
Reputation: 73376
It's because the header
you use in the printlist()
body is not the same header
than the one you refer to in main()
. These are to different variables that just happen to have the same name.
You can experiment with this principle by chaning the name of header
in printlist()
: call it for example mylist
, and the whole programme will still work.
Upvotes: 1