【发布时间】:2014-05-07 08:20:50
【问题描述】:
我不知道这段代码有什么问题。当我“显示”从“添加”输入的项目时,会显示许多不必要的项目。为什么会这样?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct list
{
char name[20];
int age;
char gender[10];
struct list *next;
};
void main(void)
{
struct list *HEAD = NULL;
struct list *temp, *trav;
char choice;
while(1)
{
clrscr();
printf("MENU\n");
printf("A) ADD\n");
printf("B) DISPLAY\n");
printf("X) EXIT\n");
scanf("%c", &choice);
switch(toupper(choice))
{
case 'A':
temp= (struct list*)malloc(sizeof(struct list));
printf("Fill-Up the following:\n");
printf("Name:");
fflush(stdin);
gets(temp->name);
printf("Age:");
fflush(stdin);
scanf("%d",&temp->age);
printf("Gender:");
fflush(stdin);
gets(temp->gender);
if(HEAD == NULL)
{
HEAD = temp;
}
else if(HEAD!=NULL)
{
for(trav=HEAD; trav->next != NULL; trav= trav->next);
trav->next=temp;
}
else
{
printf("Not Enough Memory!\n");
}
break;
case 'B':
if(HEAD==NULL)
{
printf("Linked List is Empty!\n");
getch();
break;
}
if(HEAD!=NULL){
for(trav=HEAD; trav != NULL; trav=trav->next )
{
printf("Name: %s\n", trav->name);
printf("Age: %d\n", trav->age);
printf("Gender: %s\n", trav->gender);
getch();
}
}
break;
case 'X':
free(HEAD);
free(trav);
free(temp);
exit(1);
break;
}
}
}
【问题讨论】:
-
当你 malloc temp 设置除下一个之外的所有元素。下一个元素必须设置为 NULL。
-
您决定忽略指针的不确定值是不明智的。例如:启动它并输入 X,然后在释放
trav和temp时立即调用 未定义的行为,两者都没有得到有效的内容。附带说明一下,这也使用了gets(),这是一个如此卑鄙的函数,已从标准库中删除,这无济于事。甚至无法检查单个函数结果,即非标准fflush(stdin),列表在完成之前可能会变得非常大。 -
@JerryJeremiah 啊!谢谢!它有效,:D 当我“显示”时不再有垃圾
-
@WhozCraig 好的,我会更改我的代码。谢谢:)
标签: c linked-list structure dynamic-allocation