我正在尝试链接列表,并且出于某种原因它没有做它应该做的事情。当我在选择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;
}
谢谢!
答案 0 :(得分:2)
一个问题是你正在为捐赠指针设置空间。您需要为结构本身分配空间。
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);
}
答案 1 :(得分:1)
答案 2 :(得分:1)
我看到有两个问题。首先是滑板车指出的问题。其次是addItem()
的第一行有内存泄漏。
编辑要回答第二个问题,您需要修复构建错误;您在reqList
中引用了main()
,但从未声明过它。
以下是代码的更正版本:
#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){
if(mylist==NULL)
return temp;
donate *front=mylist;
while(mylist->next!=NULL)
mylist=mylist->next;
mylist->next=temp;
return front;
}
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);
}
}
system("pause");
return 0;
}
答案 3 :(得分:0)
在这里进行修正
donate *front=(donate*)malloc(sizeof(donate*))
到
donate *front=(donate*)malloc(sizeof(donate))