初始化一个包含指向结构指针的指针的结构

时间:2013-09-05 12:40:08

标签: c pointers 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, &parameters);

感谢您的帮助。

2 个答案:

答案 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 *))