I’ve been curious about this for a while now, when using structures inside of arrays, as far as memory allocation is concerned, is it better to allocate a new structure for each entry in the array, or is it better to allocate enough space in the array for N structures.
//pointer based:
struct myStructure ** tmp = malloc(sizeof(struct myStructure *) * N);
tmp[0] = malloc(sizeof(struct myStructure));
tmp[0]->whatever = true;
//or structure in the array:
struct myStructure * tmp = malloc(sizeof(struct myStructure) * N);
tmp[0].whatever = true
Are there any benefits over one or the other? I feel like using the second form is better practice because you end up with fewer small malloc calls, but there might be cases where you can only use the first method.
Any insight into this?
Thanks!
In general I’d use the second way, since, if you use all the slots, it:
malloc/free(=>it’s faster and simpler to allocate/deallocate);On the other hand, the first way may be convenient if you are not going to use all the slots of the array (but you must be able to store many
structs on demand) and yourstructis very big, so saving that memory is worth the effort. Also, it may be worth if you need to change the order of yourstructs cheaply (although you could do that also with the second method by using a separated array of pointers).