[英]Creating array of struct inside another struct
我在代碼中遇到問題:
typedef struct{
int a;
int b;
} Passenger;
typedef struct{
int amount;
Passenger bus_array[amount];
} Bus;
此處未申報金額。
您有兩種選擇,都涉及動態內存分配。 最大的區別是你動態分配什么結構。
第一種選擇是使用指針而不是數組:
typedef struct{
int amount;
Passenger *bus_array;
} Bus;
一旦知道amount
的值,就可以為bus_array
分配內存:
Bus my_bus;
bus.amount = get_passenger_amount();
bus.bus_array = malloc(bus.amount * sizeof(Passenger));
第二種選擇是使用靈活的數組成員(正如我在評論中提到的):
typedef struct{
int amount;
Passenger bus_array[];
} Bus;
然后你需要動態分配Bus
結構:
int amount = get_passenger_amount();
Bus *my_bus = malloc(sizeof(Bus) + amount * sizeof(Passenger));
my_bus->amount = amount;
這兩種方法之間存在一些值得注意的差異。 最重要的是,第一種方法進行了兩個獨立且不同的分配:一個用於Bus
結構,另一個用於bus_array
。 第二種方法只有單個組合分配用於所有Bus
結構以及bus_array
。
這里
typedef struct{
int amount;
Passenger bus_array[amount];
} Bus;
當編譯器看到下面的語句
Passenger bus_array[amount];
它不知道要為bus_array
分配多少內存,因為在此階段編譯器的amount
未知。 因此它拋出錯誤。
代替
Passenger bus_array[amount];
您可以使用
Passenger *bus_array;
稍后,當編譯器知道amount
是amount
時,您可以為bus_array
分配等於amount
字節的內存。
添加到@Achai 的正確答案中,並且因為你問了,我會像這樣為乘客分配內存:
typedef struct{
int amount;
Passenger *bus_array;
} Bus;
Bus emptyBus = { 0, NULL}; // use this to initialize new buses so that pointer and amount are zero.
void changeAmount(Bus *bus, int amount)
{
bus->amount = amount;
free(bus->bus_array); // freeing a null pointer is OK.
bus->bus_array = malloc(sizeof(Passenger)*amount);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.