指针、链表和函数
Pointers, linked list and function
这是我的第一个问题!
我使用链表和函数。
我创建了这个函数,它将值从结构 (Passenger) 复制到链表 LIST1。
typedef struct
{
char fillname[40]
}PASSENGERS;
typedef struct list1
{
char fullname[40];
struct list1 *next;
}LIST1;
//COPYLIST
copylist(LIST1 *list1, PASSENGERS *passenger)
{
LIST1 *start=NULL;
for (i=0;i<40;i++)
{
list1 = (LIST1 *) malloc (sizeof(LIST1));
list1->next = NULL;
strcpy(list1->fullname,passenger[i].fullname);
if (start ==NULL)
start = list1;
else //add new node at the beginning of list
{
list1->next = start;
start = list1;
}
}
}
在 Main 中,我使用以下语句调用该函数
int main ()
PASSENGERS *passenger;
int h;
LIST1 *list1;
list1=copylist(list1,passenger);
但是我用 :
打印时什么也得不到
LIST1 *current = list1;
while (current !=NULL)
{
printf("%s",current->fullname);
current = current->next;
如果我不使用函数并将代码移到 main 中,一切正常,所以可能是指针的问题,我仍在尝试使用它!
谢谢
像这样修改你的复制列表函数:-
LIST1 *copylist(LIST1 *list1, PASSENGERS *passenger)
{
LIST1 *start=NULL;
int i=0;
for (i=0;i<40;i++)
{
list1 = (LIST1 *) malloc (sizeof(LIST1));
list1->next = NULL;
strcpy(list1->fullname,passenger[i].fullname);
if (start ==NULL)
start = list1;
else //add new node at the beginning of list
{
list1->next = start;
start = list1;
}
}
return start;
}
这是我的第一个问题! 我使用链表和函数。
我创建了这个函数,它将值从结构 (Passenger) 复制到链表 LIST1。
typedef struct
{
char fillname[40]
}PASSENGERS;
typedef struct list1
{
char fullname[40];
struct list1 *next;
}LIST1;
//COPYLIST
copylist(LIST1 *list1, PASSENGERS *passenger)
{
LIST1 *start=NULL;
for (i=0;i<40;i++)
{
list1 = (LIST1 *) malloc (sizeof(LIST1));
list1->next = NULL;
strcpy(list1->fullname,passenger[i].fullname);
if (start ==NULL)
start = list1;
else //add new node at the beginning of list
{
list1->next = start;
start = list1;
}
}
}
在 Main 中,我使用以下语句调用该函数
int main ()
PASSENGERS *passenger;
int h;
LIST1 *list1;
list1=copylist(list1,passenger);
但是我用 :
打印时什么也得不到LIST1 *current = list1;
while (current !=NULL)
{
printf("%s",current->fullname);
current = current->next;
如果我不使用函数并将代码移到 main 中,一切正常,所以可能是指针的问题,我仍在尝试使用它! 谢谢
像这样修改你的复制列表函数:-
LIST1 *copylist(LIST1 *list1, PASSENGERS *passenger)
{
LIST1 *start=NULL;
int i=0;
for (i=0;i<40;i++)
{
list1 = (LIST1 *) malloc (sizeof(LIST1));
list1->next = NULL;
strcpy(list1->fullname,passenger[i].fullname);
if (start ==NULL)
start = list1;
else //add new node at the beginning of list
{
list1->next = start;
start = list1;
}
}
return start;
}