![](/img/trans.png)
[英]Referencing a pointer to a struct that contains a pointer to a pointer to a struct
[英]Initialize a struct that contains pointer to a pointer to a struct
我想初始化一個包含不同類型變量的結構。 例如,假設我有
struct population {
int *ids;
double *incomes;
struct good **goodsdistn; // This is the one I am having trouble with.
};
struct population popn;
我想使用另一個結構中定義的參數來初始化popn
struct params {
int numpeople;
// there are other parameters here, not relevant for the question.
};
struct params parameters = {.numpeople = 50};
要初始化popn
我正在考慮執行以下操作:
(1)在main()
之外定義以下函數
void create_population(struct population *popn, struct params *parameters)
{
popn -> ids = malloc(sizeof(int) * parameters -> numpeople); //This works
popn -> incomes = malloc(sizeof(double) * parameters -> numpeople); //This works
popn -> goodsdistn = malloc(sizeof(???) * parameters -> numpeople);
// What do I put in place of ??? when I have a pointer to a pointer to struct good.
}
(2)在main()
調用此函數以初始化popn(隨后我可以填充struct成員):
create_population(&popn, ¶meters);
謝謝你的幫助。
如評論中所述,我還認為struct good **
是過大的,但是您知道可以對變量使用sizeof
嗎?
void create_population(struct population *popn, struct params *parameters)
{
popn -> ids = malloc(sizeof(popn->ids[0]) * parameters -> numpeople);
popn -> incomes = malloc(sizeof(popn->incomes[0]) * parameters -> numpeople);
popn -> goodsdistn = malloc(sizeof(popn->goodsdistn[0]) * parameters -> numpeople);
}
如果確實要使用類型標識符,則可以使用sizeof(struct good *)
或通用sizeof(void *)
。 所有數據指針在C中的大小均相同。
您想要以下位置代替???
:
malloc(sizeof(struct good *))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.