![](/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.