Suppose I have a following linked list structure:
struct linked_list
{
struct linked_list *next;
int data;
};
typedef struct linked_list node;
And the following function to print the linked list:
void print(node *ptr)
{
while(ptr!=NULL)
{
printf("%d ->",ptr->data);
ptr=ptr->next;
}
}
Now in the main() function when I write this:
print(head); // Assume head is the pointer pointing to the head of the list
This is essentially call-by-value. Because ptr in print will receive a copy of head. And we can’t modify head from the print() function because its call-by-value.
But my doubt is, since ptr receives a copy of head but it’s able to print the value of linked list. So does that means the print() function receives whole copy of linked list? If it does not receives the whole copy of linked list how its able to print the list?
printreceives a copy of the address of head, which means that the data representingheadisn’t copied: the function is using the actual head and hence the actual linked list, not a copy.The implications are that you can change
head, e.g.head->data, and you can modify the rest of the linked list. The only thing that you can’t do is change which node your passed-in pointer points to, i.e. you can’t dohead = NULLinprintand expect that to be reflected outsideprint.So, any of the following changes are all reflected outside the function:
The following aren’t: