gpt4 book ai didi

C - 检查指针是否为 NULL 时出现段错误

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

所以每次我尝试检查指针变量是否为 NULL 时都会遇到此段错误。错误来自添加函数中的这些代码行:

if (it->head == NULL){
printf("worksfine");
}

这是我的全部代码:

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef struct Node{
int val;
struct Node *prev;
struct Node *next;
} node;

typedef struct IteratorInt{
node *head;
node *tail;
node *last;
} IteratorInt;

IteratorInt IteratorIntNew(){
IteratorInt *listint;
listint = malloc(sizeof(IteratorInt));
listint->head = NULL;
listint->tail = NULL;
listint->last = NULL;
printf("address made %u\n", listint);
return *listint;
}

int add(IteratorInt *it, int v){
node *n;
n->val = v;
n->next = NULL;
n->prev = NULL;
printf("func works\n");
printf("n %d\n", n->val);
printf("address %u", it);
it->head = n;
printf("result %d", it->head->val);
if (it->head == NULL){
printf("worksfine");
}
/* if (it->head == 0){
it->head = n;
}
if (it->tail == 0){
it->tail = n;
}
if (it->last == 0){
it->last = n;
}*/

return 1;
}

int main() {
IteratorInt lit = IteratorIntNew();
printf("works %u", &lit);
add(&lit, 10);

/*printf("Node value %d\n", lit.head.val);
add(&lit, 15);
printf("Node value %d", lit.tail.val);*/
return 0;
}

你能告诉我它有什么问题吗?以及如何解决?非常感谢。

最佳答案

在您的add 函数中,变量n 是一个未初始化的指针。所以这不是检查it->head的问题。

关于C - 检查指针是否为 NULL 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47745046/

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