gpt4 book ai didi

c - C错误中的LinkedList

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

我正在尝试用 C 编写一个 LinkedList。这是我的两个结构

struct node{
int key;
int value;
struct node *next;
};

struct LinkedList {
struct node *head;
};

下面是我如何创建一个新节点。

void createNode(int key, int value) {
struct node *new_node;
new_node->key = key;
new_node->value = value;
new_node->next = lList->head;
lList->head = new_node;
}

我正在尝试使用下面的函数遍历 LinkedList。

void traverseNode(struct LinkedList *lList) {
struct node current = *lList->head;
while(current != NULL) {
printf("%i", current->key);
current = current->next;
}
}

但是,我一直收到错误提示

invalid operands to binary expression ('struct node'
and 'void *')

关于我的 while 表达式。

另外,我得到一个错误

printf("%i", current->key);
current = current->next

错误是

member reference type 'struct node' is not a pointer; maybe you meant to use '.'

我很困惑,因为我认为在我的节点结构中,*next 被定义为指针,因此只能使用间接 (->) 语法访问。

我是指针的初学者,因此非常感谢您的帮助。

最佳答案

您不能将 NULL 与非指针类型进行比较。

将变量 current 声明为指针 + 删除对 head 的解引用,它将编译

struct node * current = lList->head;
^ ^
while(current != NULL) // Now you can compare them

您正在获取 SEGFAULT,因为您取消引用未初始化的指针。在堆上分配足够的内存(动态存储持续时间)。

struct node *new_node = malloc(sizeof(struct node));

因为current是指针

printf("%i", current->key);
current = current->next;

现在应该没问题了。

关于c - C错误中的LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45823558/

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