gpt4 book ai didi

c - 为什么我无法显示正确的列表值?

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

为了检查示例列表实现,我尝试了以下代码。但每当我尝试显示结果时,它就会进入循环。我找不到哪里出错了。

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

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

int main()
{
int ch,num;

node *head=NULL;
head=(node *)malloc(sizeof(node));
node *new=NULL;
new=(node *)malloc(sizeof(node));
node *temp=NULL;
temp=(node *)malloc(sizeof(node));
printf("\n1.Insert to list");
printf("\n3.Display the list");
printf("\n Enter Choice->");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\n Enter data->");
scanf("%d",&num);
new->data=num;
new->next=NULL;
head->next=new;
break;

case 3: temp=head;
while(temp!=NULL)
{
printf("\n %d",temp->data);
temp=temp->next;
}


break;
default:printf("Wrong Choice");
break;

}
return 0;
}

最佳答案

这里有两个错误。

  1. 您仅分配“new”一次。这意味着每次用户输入“1”时您都会重复使用同一节点,并将其实际链接到自身。
  2. 您根本不应该为“temp”分配节点,因为您没有使用它。实际上,您使用此行丢失了指向已分配节点的指针:case 3: temp=head; 这称为“内存泄漏”。

我建议你多研究一下指针;他们似乎让你感到困惑。

关于c - 为什么我无法显示正确的列表值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12941043/

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