I have a question about passing via pointers in C. I will illustrate my question through this code snippet that I wrote:
int main () {
List *head = (List *)malloc(sizeof(List));
head->data = 0;
head->next = NULL;
insertEnd(head, 3);
//List *temp = head;
insertEnd(head, 4);
PrintList(temp);
return 0;
}
void insertEnd(List *node, int elem) {
while (node->next != NULL) {
node = node->next;
}
List *new_node = (List *)malloc(sizeof(List));
new_node->data = elem;
new_node->next = NULL;
node->next = new_node;
}
void PrintList(List *node) {
while (node) {
printf ("%i ->", node->data);
node = node->next;
}
}
In the above code snippet, I create a List pointer called head, and pass it into my insertEnd() function two times. If you notice in my insertEnd() function, I am actually moving this passed in pointer along by doing a "node->next"
If I am changing the address this pointer points to within my insertEnd() function, then how come when I call PrintList() its as if the head pointers location never moved!
PrintList() returns: "0 -> 3 -> 4 ->"
Is this because when passing by pointer, you are actually passing a new physical copy of the pointer into the function, similar to passing by value, except in this case instead of copying over the entire value/data structure you simply copy over the pointer variable? I hope this makes sense..