0

I'm a little confused about the implementation of linked.c, specifically in the function insert_node(). The first thing we want to do there is to create a new node. They proceed to create a pointer to a node (node*). Why can't we just create a new actual node, as by

 node new_node

instead of a pointer to a node? Is it just because we don't necessarily want it to disappear when the function returns? If that's the answer, I guess it also answers my next question, which was why don't we have to malloc anything for curr and prev. I guess we'd be content for those variables and anything in them to go away when the function returns.

Am I on the write track with the differences in how those three pointers were declared?

Another follow up question. Is that pretty much always the answer when you're working with some values in a function that you want to be able to use in main()? Instead of declaring a local variable, create a pointer and malloc some space instead?

1 Answer 1

2

I thought about this as well today, and your answer to your own question is right. We malloc heap memory to permanently (until you free it once the programme has ended) store a new node. The return value is a pointer to this new node, as in

node* new_node = malloc(sizeof(node));

If we didn't do that, and instead just used node, as you suggested, the memory for that particular node would be allocated to the stack, which is cleared once the function has executed, so it would be inaccessible to us during the rest of the programme (because it would have been cleared from stack).

As for the curr and prev pointers, you're again right: We don't care about them anymore once the function has executed. They are only important to temporarily store the values of the node we're looking at and the one before that. But we don't need those values anymore once we have inserted a new node into our linked list.

This is the same reason why the swap function only works if we use two pointers as parameters rather than two integers (if it is ints we want to swap). Were we to use ints instead, we would be swapping copies of the actual values, not the actual ints we use as input. Although this case is a bit different, we also use pointers within the function declaration to access values that are also accessible via main. They also don't vanish after the function has executed.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .