[英]LinkedList in C error
我正在尝试用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
错误是
成员引用类型“结构节点”不是指针; 也许您打算使用'。
我很困惑,因为我认为在我的节点结构中, *next
被定义为指针,因此只能使用indirection(->)语法进行访问。
我是指针的初学者,因此可以提供任何帮助。
您不能将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;
现在应该可以了。
由于错误指出当前是一种结构,而不是指针
将其更改为struct node *current = lList -> head;
记住指针本身没有被引用对象的存储
do{
printf("%i", current->key);
current = current->next;
} while(current != NULL)
而是通过查看下一个节点是否为空而不是整个结构来检查您是否在最后一个节点上
void createNode(int key, int value) {
struct node *new_node; // you need to malloc here
new_node->key = key;
new_node->value = value;
new_node->next = lList->head;
lList->head = new_node;
}
您必须先malloc才能访问指针。
struct node *new_node = (struct node*)malloc(sizeof(struct node));
也变像
struct node current = *lList->head;
进入
struct node *current = *lList->head;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.