我有以下代码:
main()
{
struct passenger_node {
char *name;
struct passenger_node *next;
};
struct flight {
char airline[MAXNAME];
int number;
struct passenger_node *passengers;
};
// New passengers are added to the front of the list of passengers.
void add_passenger(char *name, struct flight *flp) {
struct passenger_node n;
n.name = malloc(strlen(name)+1);
strncpy(n.name, name, strlen(name)+1);
n.next = flp->passengers;
};
void list_passengers(struct flight fl) {
printf("%s", fl.passengers->name);
}
struct flight my_flight;
strcpy(my_flight.airline, "Air");
my_flight.number = 111;
my_flight.passengers = NULL;
add_passenger("MMM", &my_flight);
list_passengers(my_flight);
}
我在函数list_passengers中的line fl.passengers->名称出现分段错误?谁能告诉我为什么会这样?
答案 0 :(得分:3)
您的add_passenger
无法更新passengers
指针:
void add_passenger(char *name, struct flight *flp) {
struct passenger_node n;
n.name = malloc(strlen(name)+1);
strncpy(n.name, name, strlen(name)+1);
n.next = flp->passengers;
flp->passengers = ???; //<--- UPDATE HERE
};
您必须为此动态分配passenger_node
,并且不能使用本地的。{/ p>
void add_passenger(char *name, struct flight *flp) {
struct passenger_node *np = malloc(sizeof(struct passenger_ndoe));
if (!np) return;
np->name = malloc(strlen(name)+1);
strncpy(np->name, name, strlen(name)+1);
np->next = flp->passengers;
flp->passengers = np;
};
您的list_passengers
也不正确。它只显示第一位乘客,并且不检查空乘客名单:
void list_passengers(struct flight fl) {
struct passenger_node *np;
for ( np = fl.passengers; np != NULL; np = np->next )
printf("%s\n", np->name);
}
答案 1 :(得分:1)
如果您将list_passengers()
更改为:
void list_passengers(struct flight fl) {
assert(fl.passengers != NULL);
printf("%s", fl.passengers->name);
}
您将看到fl.passengers == NULL
,并尝试取消引用它。
答案 2 :(得分:1)
你基本上需要这个(应该用任何C编译器编译):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNAME 100
struct passenger_node {
char *name;
struct passenger_node *next;
};
struct flight {
char airline[MAXNAME];
int number;
struct passenger_node *passengers;
};
// New passengers are added to the front of the list of passengers.
void add_passenger(char *name, struct flight *flp) {
struct passenger_node *newpassenger ;
newpassenger = malloc(sizeof (struct passenger_node));
newpassenger->name = malloc(strlen(name)+1);
strncpy(newpassenger->name, name, strlen(name)+1);
newpassenger->next = flp->passengers;
flp->passengers = newpassenger;
};
void list_passengers(struct flight fl) {
printf("%s", fl.passengers->name);
}
main()
{
struct flight my_flight;
strcpy(my_flight.airline, "Air");
my_flight.number = 111;
my_flight.passengers = NULL;
add_passenger("MMM", &my_flight);
add_passenger("XXX", &my_flight);
list_passengers(my_flight);
}
但您仍需要使list_passengers
功能正常工作。目前只打印列表中的第一位乘客。
答案 3 :(得分:0)
C中不允许使用嵌套函数。您在main中定义了函数,这是函数
name
是一个指针,你可以为它分配内存。分配menmory然后访问它并确保您不访问NULL指针。这会导致分段错误。