필자는 연결된 목록을 사용하여 작동하는 이전 프로그램을 업데이트하려고합니다. 버스의 좌석 수를 포함하는 txt 파일이 있습니다. 이 bus.txt 파일을 읽은 다음 특정 연결 목록 및 numberofseats (예 : 45 석)의 메모리를 동적으로 할당합니다. 다음 코드를 작성하여 작동 원리를 테스트하고 각 승객의 전체 이름에 A를 넣으려고 시도합니다. phonenr 등에 0을 넣으려고합니다. 45 자리를 인쇄하여 잘 작동하는지 확인하려고 할 때 무한 루프를 얻고 A는 영원히 인쇄됩니다 .. 나는 무엇이 누락 되었습니까?연결된 목록 초기화
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int i,j,numberofseats,temp;
char platenr[8],selection;
char firstname[20],lastname[20];
char phone[11];
char *p;
typedef struct psg
{
char fullname[40];
unsigned short phonenr[10];
unsigned int seatnr;
struct psg *next
}PASSENGERS;
PASSENGERS* readfile(char *platenr, int *seatnr)
{
char buff[60];
FILE *businfo;
businfo = fopen ("bus.txt","r");
if (businfo == NULL)
{
printf("Error Opening File, check if file bus.txt is present");
exit(1);
}
else
{
fscanf(businfo,"%s %d",platenr, seatnr);
printf("Bus Licence plate Nr is: %s, and Number of Seats is: %d", platenr, *seatnr);
PASSENGERS *p = malloc(*seatnr * sizeof(PASSENGERS));
if (p==NULL)
{
puts("Unable to allocate memory");
exit(1);
}
return p;
}
}
int main()
{
PASSENGERS *passenger, *tmp, *start=NULL;
passenger = readfile(platenr,&numberofseats);
for (i=0;i<numberofseats;i++)
{
passenger->next=NULL;
strcpy (passenger->fullname,"A");
passenger->seatnr=i+1;
for (j=0;j<10;j++)
passenger->phonenr[j]=0;
if (start==NULL)
start=passenger;
else{
tmp=start;
while (tmp->next !=NULL) tmp=tmp->next;
tmp->next=passenger;
}
}
tmp=start;
while(tmp!=NULL)
{
printf ("%s",tmp->fullname);
tmp=tmp->next;
}
}
하나의 malloc 호출에 N 개의 PASSENGERS * 배열 *을 할당했습니다. 어레이에 순차적으로 할당 할 의향이 있습니까? 그렇다면 왜? 일반적으로 승객 당 한 번에 하나씩 할당하고 함께 연결합니다. – jarmod
이것은 링크 된 목록이 아닙니다. 연결된 목록에서 ** 노드를 ** 추가 ** 제거 ** 할 수 있습니다. 당신은 당신의 방식대로 할 수 없습니다. –