연결된 목록 항목을 처음 사용하고 방금 연결된 목록을 사용하여 첫 번째 프로그램을 만들었으므로 구조에 데이터를 저장하지 않는 것이 문제입니다. 잘 실행되지만 오류는 없지만 인쇄 할 때 데이터가 표시되지 않습니다. 여기 내 코드가있다.C에서 연결된 목록 사용
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
int nID;
char chTitle;
struct node* next;
};
void addList(struct node *head);
void printList(struct node *head);
int checkID(struct node *head, int t);
int main(int argc, const char * argv[])
{
int nInput;
struct node *head = NULL;
while (1)
{
printf("\n\t\t~~MENU~~\n");
printf("1. Add a new book\n");
printf("2. Print all data\n");
printf("3. Exit\n");
printf("Make your selection: ");
scanf("%d", &nInput);
switch (nInput)
{
case 1:
addList(head);
break;
case 2:
printList(head);
break;
case 3:
printf("\nGoodby!!! Thanks for using the program\n");
exit(1);
break;
default:
printf("\n\t\t~~Invalid Input~~\n");
break;
}
}
return 0;
}
void addList(struct node *head)
{
int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
printf("\n Enter Book Details\n");
printf("Enter book ISBN: ");
scanf("%d", &bookId);
int bInd = checkID(head, bookId);
if (bInd == 0)
{
printf("Enter title: ");
scanf("%s", &temp->chTitle);
temp->next = head;
head = temp;
}
else
{
printf("\nSorry another book using that id!\n");
}
}
void printList(struct node* head)
{
while (head != NULL)
{
printf("%s", &head->chTitle);
head = head->next;
}
}
int checkID(struct node *head, int t)
{
head = NULL;
while (head != NULL)
{
if (head->nID == t)
return 1;
head = head->next;
}
return 0;
}
StackOverflow는 코드에 대한 자유로운 질문에 대답하지 않습니다. 여기서 질문을 할 때 문제를 해결하기 위해 무엇을 시도했는지 설명 할 수 있도록 준비해야합니다. 아직 디버거를 사용해 보셨습니까? – Tom
추천 : ['malloc'의 결과를 캐스팅하지 마세요.] (0120-139904) –
'addList()'는'head'를 로컬로만 변경합니다. 그래서'main'의'head'는 항상 null입니다. –