我想初始化一個包含不同類型變量的結構體。例如,假設我有初始化一個包含指向結構體指針的指針的結構體
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(以後我就可以填滿結構成員):
create_population(&popn, ¶meters);
感謝您的幫助。
爲什麼'struct good ** goodsdistn'而不是'struct good * goodsdistn'? – trojanfoe
@trojanfoe'goodsdistn'將是'struct good pointers'的數組。但我會進一步思考這個問題。 – Curious2learn