[英]C Heap Allocating a Hard Coded Struct Array
I am having trouble figuring out how to make a hard-coded array heap allocated. 我在弄清楚如何分配硬编码数组堆时遇到麻烦。
Imagine I have the structures: 假设我有以下结构:
struct my_struct
{
...
};
struct holder
{
my_struct *array_of_struct;
...
};
Now to create an instance of struct holder
though, the array of struct my_struct
has to be hard-coded, such as: 现在来创建的一个实例
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;
}
This assignment though wont work, because its pointing to arr
which is stack allocated. 尽管此分配不会起作用,因为它指向已分配堆栈的
arr
。 How would I go about making this assignment of holder->array_of_struct
heap allocated? 我将如何分配该
holder->array_of_struct
堆分配?
The super-lazy way to do it is just copy the array into a buffer from malloc()
, as follows: 超级懒惰的方法是将数组从
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;
By "super-lazy" I mean "minimum number of lines of code written". “超级懒惰”是指“所写代码的最小行数”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.