我不知道這段代碼有什麼問題。當我「顯示」我從「添加」中輸入的項目時,會顯示許多不必要的項目。這是爲什麼發生?C編程中的鏈表
#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)',該列表在完成之前可能會變得非常大。 – WhozCraig
@JerryJeremiah啊!謝謝!它的工作原理,:d沒有更多的垃圾,當我「顯示」 – JayrCastro