简体   繁体   中英

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 *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. How would I go about making this assignment of holder->array_of_struct heap allocated?

The super-lazy way to do it is just copy the array into a buffer from malloc() , as follows:

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM