이 코드의 문제점을 모르겠습니다. "ADD"에서 입력 한 항목을 "표시"할 때 많은 불필요한 항목이 표시됩니다. 왜 이런 일이 일어나는 걸까요?C 프로그래밍의 연결된 목록
temp= (struct list*)malloc(sizeof(struct list));
을하지만 당신은 당신의 구조의 값을 초기화하지 :
#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