gpt4 book ai didi

c - 在这种情况下,通过指针或通过值传递结构有什么区别?

转载 作者:行者123 更新时间:2023-12-04 11:40:07 25 4
gpt4 key购买 nike

所以我正在阅读 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.

我的问题是为什么第一个功能有效而第二个功能无效?

最佳答案

问题是您使用的是所谓的灵活数组成员,规范对此有说明:

In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.

因此,当您按值传递它时,不会复制座位本身。当你通过指针传递它时,指针指向原来有座位的平面,所以它有效..

关于c - 在这种情况下,通过指针或通过值传递结构有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47379515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com