c - Odd problem with pointer while implementing a linked list -
i'm trying implement linked list in c, , want store head node in separate struct. however, seems head node being reassigned somehow whenever add node.
#include <stdio.h> #include <stdlib.h> struct bc_node { struct bc_node *next; void *data; }; struct bc_list { struct bc_node *head; struct bc_node *tail; }; void bc_list_push(struct bc_list *list, void *data) { struct bc_node *node = calloc(1, sizeof(struct bc_node)); if (list->head != null) printf("head: %d\n", *((int *) (list->head)->data)); node->next = null; node->data = data; if (list->head == null) { printf("head null.\n"); list->head = node; } if (list->tail != null) { (list->tail)->next = node; } list->tail = node; printf("head: %d\n", *((int *) (list->head)->data)); } int main(void) { int i; struct bc_list *list = calloc(1, sizeof(struct bc_list)); list->head = null; list->tail = null; (i = 0; < 3; i++) bc_list_push(list, &i); return 0; }
the output:
head null. head: 0 head: 1 head: 1 head: 2 head: 2
your data
member pointer variable i
in main
, when print *data
see value of counter during round of loop. nodes have same data value!
Comments
Post a Comment