gpt4 book ai didi

c - 空指针赋值错误

转载 作者:行者123 更新时间:2023-11-30 18:20:17 29 4
gpt4 key购买 nike

这是一个简单的链接列表 C 程序,它显示了一些运行时错误!“空指针赋值”

从未听说过它,并且我在代码中没有看到任何错误?

我应该做什么?

#include <stdio.h>
#include<conio.h>

typedef struct node
{
int data;
struct node *next;
}node;

void main()
{
node *head,*P;
int n,i;

printf("Enter no. of elements\n");
scanf("%d",&n);

printf("Enter %d data elements\n",n);
head=(node*)malloc(sizeof(node));
scanf("%d",&(head->data));
head->next = NULL;
P=head;
for(i=1;i<n;i++)
{
P->next=(node*)malloc(sizeof(node));
P=P->next;
P->next=NULL;
scanf("%d",P->data);
}

while(P!=NULL)
{
printf("%d",P=P->data);
P=P->next;
}

}

最佳答案

这里有很多错误:

  • malloc在范围内没有原型(prototype)的情况下调用。 (要修复,#include <stdlib.h>)。
  • malloc的返回值未检查
  • scanf("%d",P->data);应该是scanf("%d",&P->data);
  • printf("%d",P=P->data);应该是printf("%d",P->data);

您应该已经收到关于其中大部分内容的警告。不要忽略编译器输出消息。

其中任何一个都可能导致您的错误(尽管我猜测 P=P->data 最有可能)。

另外,重置 P = head;在尝试打印列表之前,否则您将从末尾开始,因此您将不会得到任何输出。

关于c - 空指针赋值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26698844/

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