gpt4 book ai didi

c - c中的链表问题

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

我正在尝试链表,但出于某种原因它没有按照预期进行。当我在选择 1 后输入数量时,一切都很好,直到将节点添加到现有列表中,之后数量变成一串奇怪的数字。而且,每当我尝试向捐赠列表添加多个节点时,程序就会崩溃。

编辑:上面的问题已经解决了,但是还有一个我忘了说的问题当我尝试打印列表时,什么也没有打印出来。当我选择 4 时会发生这种情况。

EDIT2:打印功能只打印出第一个节点,之后什么也没有。请帮忙。

这是代码。

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

typedef struct donation{
char name[50];
int quant;
struct donation* next;
}donate;


donate* addItem(donate *mylist,donate *temp){
donate *front=(donate*)malloc(sizeof(donate*));

if(mylist==NULL)
return temp;

front=mylist;
while(mylist->next!=NULL)
mylist=mylist->next;
mylist->next=temp;

return front;
}
void print(donate* donList){

printf("Printing the Donations Table\n\n");
if(donList!=NULL){
while(donList->next!=NULL){
printf("%s %d\n",donList->name,donList->quant);
donList=donList->next;
}
}
}

main(){

donate *list=NULL;

while(1){
int choice;
printf("1. Add a donation\n);
printf("Enter your choice: ");
scanf("%d",&choice);

if(choice==1){
donate* temp=(donate*)malloc(sizeof(donate*));
printf("\nEnter inventory type: ");
scanf("%s",temp->name);
printf("Enter the amount: ");
scanf("%d",&temp->quant);
temp->next=NULL;
list=addItem(list,temp);
printf("\nDonation Added!\n");
printf("%s %d\n",list->name,list->quant);
}
else if(choice==4){
print(list);
}
}

system("pause");
return 0;
}

谢谢!

最佳答案

一个问题是您正在为捐赠指针分配空间。您需要为结构本身分配空间。

donate* temp=(donate*)malloc(sizeof(donate*));

应该是

donate* temp= malloc(sizeof(donate));

由于您正在执行 malloc,因此在添加项目之前,我认为 addItem 只需要:

donate* addItem(donate *mylist,donate *temp)
{
if (mylist != NULL)
temp->next = mylist;

return temp;
}

看起来您不会打印 1 项列表:

   printf("Printing the Donations Table\n\n");
if(donList!=NULL){
printf("Not NULL!!!!\n");
while(donList->next!=NULL){
printf("%s %d\n",donList->name,donList->quant);
donList=donList->next;
}
}

我认为应该是:

printf("Printing the Donations Table\n\n");
if (donList!=NULL)
{
printf("Not NULL!!!!\n");
do
{
printf("%s %d\n",donList->name,donList->quant)
donList=donList->next;
}
while(donList != NULL);
}

关于c - c中的链表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12557753/

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