我想初始化一个包含不同类型变量的结构。例如,假设我有
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);
感谢您的帮助。
答案 0 :(得分:1)
正如评论中所提到的,我也认为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中具有相同的大小。
答案 1 :(得分:0)
您希望以下代替???
:
malloc(sizeof(struct good *))