Linked Lists: Pointers sent to functions as arguments do not change their valur
After long C vacations, I decided to create a linked list to see if I remembered things right. I see I don't. My linked list is supposed to be a queue.
In function mk_item, if tail equals NULL, then it means there is no linked list created. Hence, a list is created and both head and tail are forced to point into that direction. However, when this function exits, the value of head returns to the original NULL. I don't understand why, ,considering it is pointers we are talking about. What I am doing wrong? And how can I solve it? Thank you very much for your help :) Code:
|
I am slightly confused by your logic here. But I did go out with the guys after work today so that might be why.....
The way I do link lists is to declare a structure (I will call it NODE) like the one you have created with some kind of data inside it and a next pointer. I start the program with head and tail (both NODE's) pointing to null. My routine that adds data would first check to see if head is NULL. If it is it creates a new NODE (mallocs data, sets the data value, and sets the next value to NULL) and points head to this node and points tail to head->next. If head isn't null it checks to see if tail is NULL, if it is it creates a new node where tail is currently pointing. If both head and tail aren't null then tail = tail->next and we create a new node where tail is currently pointing. To pull data off the queue we simply save the data from head, and point head to head->next. This of course assumes a FIFO queue. |
I think maybe what you need to do is to pass the pointers to mk_item by reference, rather than by value. The two parameters to mk_item (list * tail, list * head) are local copies that are lost once the function returns, so if you set "tail = " something, it's only for the scope of that function.
So try this: list * mk_item( list * &tail, list * &head ) ... |
wapcaplet is right but references are C++ if your doing it in C(seems like you are) you'll have to do it with a double pointer, redeclare mk_item like this
list* mk_item(list* tail, list** head) { and call it with mk_item(tail, &head) |
All times are GMT -5. The time now is 12:39 AM. |