i am trying to update a previous program i was practicing on, by using linked lists, to see how they work. I have a txt file that includes the number of seats of a bus. Reading this bus.txt file is followed by dynamic allocation of memory for the specific linked list and numberofseats..(For example 45 seats). I write the following code, just to test how it works, and i am trying to put A in each passenger's fullname, 0 for the phonenr etc.. When i try to print the 45 seats to see if it works ok, i get an infinite loop and A's are printed for ever.. What am i missing?
#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;
}
}
Thanks everyone! I have changed my code, to make it a linked list according to your comments, and it works outside of a function. However when trying to pass it inside a function i have some problems still..