我是一个有帮助的助手,可以为您进行翻译。以下是需要翻译的内容:
所以我正在学习《C Primer Plus》这本书,遇到了一个关于结构体和文件的编程任务。主要目标是为飞机制作一个座位预订程序。
我定义了以下结构体:
typedef struct {
unsigned short identification_number;
unsigned short status;
char last_name[MAX_NAM_LEN];
char first_name[MAX_NAM_LEN];
} Seat;
typedef struct {
unsigned short empty_seats;
Seat seats[]; // Flexible Array Member
} Plane;
我有以下函数,用于打印出空座位的身份证号码。
/*
* Function: print_empty_seats_ID
* -------------------------
* Prints a list of empty seats identification numbers of the given plane.
*
*/
void print_empty_seats_ID (Plane* plane, int num_seats) {
// Clear the screen.
system("clear");
printf("Identification number of empty seats:");
for (int i = 0; i < num_seats; i++) {
if (plane->seats[i].status == EMPTY)
printf(" %d", plane->seats[i].identification_number);
}
puts("");
// Redirect the user to the main menu.
puts("Redirecting in 4 seconds...");
sleep(4);
}
这个函数是这样被另一个函数调用的,
print_empty_seats_ID(plane, num_seats)
,其中plane
是之前在堆上定义的指向飞机结构体的指针,num_seats
是飞机上座位的总数。
虽然此函数有效,但如果我改成使用按值调用而非指针,则会打印出垃圾值,如下所示。
/*
* Function: print_empty_seats_ID
* -------------------------
* Prints a list of empty seats identification numbers of the given plane.
*
*/
void print_empty_seats_ID (Plane plane, int num_seats) {
// Clear the screen.
system("clear");
printf("Identification number of empty seats:");
for (int i = 0; i < num_seats; i++) {
if (plane.seats[i].status == EMPTY)
printf(" %d", plane.seats[i].identification_number);
}
puts("");
// Redirect the user to the main menu.
puts("Redirecting in 4 seconds...");
sleep(4);
}
在这种情况下,该函数被这样调用:
print_empty_seats_ID (*plane, num_seats);
并输出以下无意义的内容:Identification number of empty seats: 64 0 0
。我的问题是第一个函数为什么能够工作而第二个函数不能?
struct
的大小会是多少。 - Weather Vane