gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:08:09 25 4
gpt4 key购买 nike

我正试图在 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;
}

输出:

head is null.
head: 0
head: 1
head: 1
head: 2
head: 2

最佳答案

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

关于c - 实现链表时指针的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6562362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com