实现链表时指针奇怪的问题

Bra*_*man 0 c struct pointers linked-list

我正在尝试在C中实现一个链表,我想将头节点存储在一个单独的结构中.但是,每当我添加另一个节点时,似乎都会以某种方式重新分配头节点.

#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 is 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;
    for (i = 0; i < 3; i++)
        BC_list_push(list, &i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

head is null.
head: 0
head: 1
head: 1
head: 2
head: 2
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 6

你的data成员只是一个指针变量imain,所以当你打印*data你刚才看到的那轮循环的过程中计数器的值.您的所有节点都具有相同的数据值!