我是C语言的新手,我创建了一个简单的链接列表,但是我收到2条警告,我想使代码尽可能地完善。我查看了文章Dereferencing a null pointer和What does "dereferencing" a pointer mean?,但我认为我并不完全理解。我该如何摆脱它们?
1-解除引用的NULL指针“第一”。2-取消引用的NULL指针“ last”。
我的代码是:
#include <stdlib.h>
#include <stdio.h>
//define struct
typedef struct Node{
int data;
struct Node* next;
}node;
//initialise first and last pointer
node* first = NULL, *last = NULL;
void push(int data) {
node* walk = NULL, *temp = NULL;
//create a node that will be added
temp = (node*)malloc(sizeof(node));
//if first is empty, add new node to first
if (first == NULL) {
first = temp;
first->data = data;
first->next = NULL;
last = first;
}
//if first isn't empty, walk to the end, then add new node to last
else {
last->next = temp;
last = last->next;
last->data = data;
last->next = NULL;
}
}
void display() {
//create a pointer 'walk' that will start from firt, and iterate
node* walk;
walk = first;
int i = 0;
while (walk != NULL) {
printf("%d. element: %d\n", i+1, walk->data);
walk = walk->next;
i++;
}
}
int main() {
int option = NULL;
int data = NULL;
while (1) {
printf("\n1-Insert Data\n3-Display\n\n");
scanf_s("%d", &option);
switch (option) {
case 1: scanf_s("%d", &data);
push(data); break;
case 3: display(); break;
}
}
}
在if (first == NULL)
块中,您正在执行与first->data = data;
相同的(*first).data = data;
。您不能保证temp
不是NULL
(malloc
调用可能会失败),因此您应该检查一下情况是否如此。请注意,在这种情况下,first
为NULL
and,您正在尝试取消引用它。有关更多详细信息,请参见答案here。
编辑:
我猜您的预期状况为if (first != NULL)
,因此可以解决。