-1

Is there a best way to create an array of structs that resides in the heap with malloc? Specifically if I create the array initially on the heap but wont be able to create each of the entries upfront, I'd still like to be able to create the struct/entries and have them reside in the heap and be accessible from the struct. Is there a good/canonical way to do this?

Thomas M
  • 47
  • 1
  • 10
  • 2
    I'm not sure what you are asking. When you use malloc/calloc, memory is allocated on the heap. Read [this post](https://stackoverflow.com/questions/6770596/memory-allocation-in-stack-and-heap) for more details –  Jul 14 '18 at 22:51
  • 1
    Well, the best way to allocate on the heap is to use malloc. – KamilCuk Jul 14 '18 at 22:54

2 Answers2

3

If your structures are allocated on the heap, you can declare and allocate an array of pointers to each structure on the heap as well:

struct my_struct **struct_arr = malloc(sizeof(struct my_struct *) * ARR_LEN);

Where ARR_LEN is the number of structures you would like to store in the array. In that case,

struct_arr[0]

is of type *struct my_struct (pointer to my_struct).

So now, you can allocate a my_struct structure in heap memory, like this:

struct my_struct *struct_ptr = malloc(sizeof(struct my_struct));

and store the resulting pointer into the array of structures above:

struct_arr[0] = struct_ptr;
RayaneCTX
  • 573
  • 4
  • 13
0

To allocate memory is through the malloc / realloc / calloc. It is not the only way to do it, but this is the ISO C standard compliance.

In terms of accesing, it is not defined by where the variable is being allocated (stack, heap or wherever), it is defined by the scope of the way to access to the bunch of memory (to determine the scope you can use the keyword volatile, local variables, etc).

Regarding structs, you will have to "reserve" an amount of memory big enough to allocate the array. Once you get the pointer to the reserved bunch of memory, you are able to use it (in that case, for your struct), something like:

struct structType {
    int varA;
};

struct structType *structP = malloc(sizeof(struct structType));
structP->varA = 1;  
Jose
  • 3,306
  • 1
  • 17
  • 22