C堆分配硬编码结构阵列

时间:2016-01-28 23:29:19

标签: c arrays pointers struct

我无法弄清楚如何分配硬编码数组堆。

想象一下,我有结构:

struct my_struct
{
    ...
};

struct holder
{
    my_struct *array_of_struct;
    ...
};

现在要创建struct holder的实例,struct my_struct的数组必须是硬编码的,例如:

struct holder *new_holder()
{
    struct holder *my_holder = malloc(sizeof(struct holder));
    if (my_holder == NULL)
        exit(-1);

    struct my_struct arr[] = {mystruct_instace_1, mystruct_instance_2, ...};
    holder->array_of_struct = arr;
    return holder;
}

这个赋值虽然不起作用,因为它指向arr堆栈已分配。我将如何进行holder->array_of_struct堆分配的分配?

1 个答案:

答案 0 :(得分:2)

超级懒惰的方法就是将数组复制到malloc()的缓冲区中,如下所示:

struct my_struct arr[] = {mystruct_instace_1, mystruct_instance_2, ...};
holder->array_of_struct = malloc(sizeof(arr));
assert(holder->array_of_struct);
memcpy(holder->array_of_struct, arr, sizeof(arr));
return holder;

“超级懒惰”是指“写入的最小代码行数”。