Reputation: 788
I am trying to understand so called linked list in c using struct-nodes. What I want is to use the same pointer through the code but when inplementing this the for loop prints the last character. I think I understand why - probably because the pointer points at the second and the last node in the program.
The program puts two characters in to succesive nodes - the letters "h" and "e". And the purpose is to print these characters.
So the question - How do I go back to the first node using this pointer? Is the only answer to create two pointer - i.e. one pointer called for example startpointer and another pointer called nextpointer? Or could I somehow use one and same pointer throug the code?
thanks!
#include <stdio.h>
#include <stdlib.h>
struct listNode {
char c[2];
struct listNode *ptrNextNode;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
int main(void) {
ListNode list_node;
ListNodePtr list_node_ptr;
list_node_ptr = malloc(sizeof(list_node));
strcpy(list_node_ptr->c, "h");
list_node_ptr = list_node_ptr->ptrNextNode;
list_node_ptr = malloc(sizeof(list_node));
strcpy(list_node_ptr->c, "e");
int i;
for (i = 0; i < 2; i++) {
printf("%s", list_node_ptr->c);
}
return EXIT_SUCCESS;
}
Upvotes: 0
Views: 141
Reputation: 409176
The road to the dark side comes with this assignment:
list_node_ptr = list_node_ptr->ptrNextNode;
Here you overwrite the original pointer with an uninitialized value. This makes you loose the original list_node_ptr
causing a memory leak. And if you, after the above assignment, tried to use list_node_ptr
except as a recipient to an assignment, it would have been undefined behavior.
Although, in the very next line, you overwrite the pointer again, making it again a valid pointer, and avoid the undefined behavior.
All in all, you're not making a linked list by the code in the question. You could do something like
ListNodePtr head, list_node_ptr;
head = list_node_ptr = calloc(1, sizeof(*list_node_ptr));
list_node_ptr->c[0] = 'c';
list_node_ptr->next = calloc(1, sizeof(*list_node_ptr));
list_node_ptr = list_node_ptr->next;
list_node_ptr->c[0] = 'e';
for (list_node_ptr = head; list_node_ptr != NULL; list_node_ptr = list_node_ptr->next)
printf("%s\n", list_node_ptr->c);
In the above code, I allocate the next
pointer before reassigning it to list_node_ptr
. I also save the original head of the list in the head
variable so you can iterate the list.
Upvotes: 2
Reputation: 164
Yes, you need a doubly linked list, which is to use another pointer to point to the previous node.
Upvotes: 0