gpt4 book ai didi

C 堆分配硬编码结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:21 25 4
gpt4 key购买 nike

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

假设我有以下结构:

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 堆?

最佳答案

super 懒惰的方法是将数组从 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;

我所说的“ super 懒惰”是指“编写的代码行数最少”。

关于C 堆分配硬编码结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com