I’m having a little trouble with linked lists. I don’t understand why this code will traverse and print the linked list with no issue:
struct foo {
int data;
struct foo * next;
};
int main(void) {
struct foo * bar = NULL;
...
print(bar);
}
void print(struct foo * bar) {
while (bar != NULL) {
printf("%d, bar->data);
bar = bar->next;
}
}
Yet when I place the list inside another structure, like an array, the list gets destroyed during traversal because pointers get reassigned at bar[i] = bar[i]->next:
struct foo {
int data;
struct foo * next;
};
int main(void) {
struct foo ** bar = (struct foo**)malloc(SIZE * sizeof(struct foo*));
for (i = 0; i < SIZE; i++)
bar[i] = NULL;
...
print(bar);
}
void print(struct foo ** bar) {
for (i = 0; i < SIZE; i++)
while (bar[i] != NULL) {
printf("%d, bar->data);
bar[i] = bar[i]->next;
}
}
Why does this happen? I know a proper way to write the print function in this scenario would be:
void print(struct foo ** bar) {
struct foo * helper;
for (i = 0; i < SIZE; i++)
for (helper = foo[i]; helper != NULL; helper = helper->next)
printf("%d", helper[i]->data);
}
I just want to understand why. Why do pointers not get reassigned in the first scenario, but do on the second? I assume it’s something to do with passing values vs passing references, but that would mean the first function destroys the list too. Can anyone offer some insight?
This function takes a
copy of a pointer to struct fooas a first argument. No matter what the function does with it, I am sure that the original pointer will not be modified, since I’m just working with a copy here. The value that the pointer points to on the other hand, may be modified.This function takes a
copy of a pointer to pointer to struct fooas a first argument. Once again, the original pointer to pointer cannot be modified from here, the value which it points too on the other hand, which is apointer to foohere, may be modified. Of course, the value pointed by the pointer pointed by bar, can also be modified.If you’ve understood this correctly, you should realize why passing
struct somethinginstead ofstruct something*to a function, is a bad idea performance-wise.