gpt4 book ai didi

c - 为什么不能在 if 语句中使用空指针?

转载 作者:行者123 更新时间:2023-11-30 21:20:06 25 4
gpt4 key购买 nike

我正在尝试使用列表做一个简单的作业,并且我想编写一个函数:

  1. 接收一个指向列表头部的双指针和一个整数
  2. 检查头部是否指向某物或 NULL
  3. 如果 head 指向 NULL,则将其重新分配到包含我的新节点的新内存位置[等]
  4. 如果不为空,则将新节点添加到列表底部

但是,当我的代码检查头列表是否为 NULL 时,我收到“读访问内存冲突”;这是我的代码:

void InserList(t_node** lis, int x) {
t_node* temp;
temp = malloc(sizeof(t_node));
temp->num = x;
if (*lis == NULL) {
temp->next = NULL;
*lis = temp;
}
else {
temp = *lis;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = malloc(sizeof(t_node));
temp->next->num = x;
temp->next->next = NULL;
}
}

我的代码运行没有问题,直到它必须这样做:

if (*lis == NULL) {
...
}

给我一​​个错误“lis was nullptr”。我的想法有错吗?我应该如何修复这个功能?

谢谢

编辑:这是主要功能

int main(void) {
int elements;
int count;
int tempnum;
t_node *head, *second_head;
head = second_head = NULL;
t_node **ref_head, **ref_second_head;
ref_head = &head;
ref_second_head = &second_head;
scanf("%d", &elements);
for (count = 0; count != elements; count++) {
scanf("%d", &tempnum);
InserList(head, tempnum);
if (IsPrimo(tempnum) == false) {
InserList(second_head, tempnum);
}
}
PrintList(second_head);
}

最佳答案

这就是为什么你应该在编译时发出警告。这是你要做的:

InserList(head, tempnum);

您在需要 t_node ** 的地方传递了 t_node * 。这些是不兼容的指针类型。因此,您的程序具有未定义的行为。

修复为:

InserList(&head, tempnum);

然后为您的编译器提供高级警告标志并修复您的代码,直到没有警告为止。

关于c - 为什么不能在 if 语句中使用空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43321719/

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