C语言中的链表及其函数
我创建了下面的链表,它从文件中读取数据,然后动态地将值分配给链表(例如,我通过提供一个in-fullname来初始化它。我希望该列表在函数外部可用,但我认为我有一个问题。 通过在main中打印列表,我什么都没有。。 我的代码在下面C语言中的链表及其函数,c,linked-list,C,Linked List,我创建了下面的链表,它从文件中读取数据,然后动态地将值分配给链表(例如,我通过提供一个in-fullname来初始化它。我希望该列表在函数外部可用,但我认为我有一个问题。 通过在main中打印列表,我什么都没有。。 我的代码在下面 #include <stdio.h> #include <string.h> #include <stdlib.h> int i,j,numberofse
#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;
void readfile(char *platenr, int *seatnr, PASSENGERS *passenger, PASSENGERS *tmp, PASSENGERS *start)
{
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);
for (i=0;i<numberofseats;i++)
{
passenger = (PASSENGERS *) malloc (sizeof(PASSENGERS));
if (passenger==NULL) /*elegxos orthis desmeysis mnimis*/
{
puts("Unable to allocate memory");
exit(1);
}
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;
}
}
}
}
int main()
{
PASSENGERS *passenger, *tmp, *start=NULL;
readfile(platenr,&numberofseats, passenger,tmp, start);
tmp=start;
while(tmp!=NULL)
{
printf ("%s",tmp->fullname);
tmp=tmp->next;
}
}
#包括
#包括
#包括
int i,j,座椅数量,温度;
炭板[8],选择;
char firstname[20],lastname[20];
字符电话[11];
char*p;
类型定义结构psg
{
字符全名[40];
未签名短电话号码[10];
无符号整数seatnr;
结构psg*下一步
}乘客;
无效读取文件(字符*铭牌,内部*座位,乘客*乘客,乘客*tmp,乘客*启动)
{
字符buff[60];
文件*businfo;
businfo=fopen(“bus.txt”,“r”);
if(businfo==NULL)
{
printf(“打开文件时出错,请检查文件bus.txt是否存在”);
出口(1);
}
其他的
{
fscanf(业务信息,“%s%d”,版面,座位);
printf(“公共汽车车牌号为:%s,座位数为:%d”,车牌号为*seatnr);
对于(i=0;不精确=NULL;
strcpy(乘客->全名,“A”);
乘客->座位=i+1;
对于(j=0;jphonenr[j]=0;
if(start==NULL)
启动=乘客;
否则{
tmp=启动;
而(tmp->next!=NULL)tmp=tmp->next;
tmp->next=乘客;
}
}
}
}
int main()
{
乘客*乘客,*tmp,*start=NULL;
readfile(车牌号和座位号、乘客、tmp、启动);
tmp=启动;
while(tmp!=NULL)
{
printf(“%s”,tmp->fullname);
tmp=tmp->next;
}
}
在Main侧,您将start
作为指针传递。然后更改start
内部函数readfile
的值。Main中的变量start
和readfile
中的变量start
不是同一个变量。要使此代码正常工作,您需要这是参考资料
编写时,代码将不打印任何内容,因为main中start的值没有更改
某些编译器将允许您执行以下操作
readfile(…,乘客*&start)
然后,上述代码将使main
中的变量start
和readfile
中的变量start
成为相同的变量
如果编译器不喜欢这样,则需要将指针传递给指针
readfile(…,乘客**pStart)
然后在函数中声明并设置start,如下所示
乘客*start=*pStart;
干杯请注意,它是。乍一看,请确保您将
printf
换行,否则将不会刷新缓冲区:printf(“%s\n”,tmp->fullname)
请发布到目前为止的输出结果。我在printf中添加了新行,但不起作用。如果我将用于打印的代码放在函数内部,它会正常打印。在函数外部,它不会打印。因此,主“乘客*启动”中可用的函数的结果有问题){patients*tmp,*start=NULL;:start
有重复的名称。`即使它没有重叠,也无法更改调用方变量。