Wednesday, 28 August 2013

Array of pointers vs. array of elements

Array of pointers vs. array of elements

This morning I've had a discussion with a colleague about this topic. He
says that it's always better to allocate arrays as arrays of pointers,
since allocating every single element separately has better chances to get
a free memory chunk. Somethink like this:
// Consider n_elements as a dynamic value
int n_elements = 10, i;
int **ary = (int **) malloc(sizeof(int *) * n_elements);
for(i = 0; i < n_elements; i++)
{
ary[i] = (int *) malloc(sizeof(int));
}
As opposed to his approach, I think that is better to allocate arrays of
elements, just because you'll get a compact memory chunk and not a bunch
of references spread around the heap. Something like this:
int n_elements = 10, i;
int *ary = (int *) malloc(sizeof(int) * n_elements);
ary[0] = 100;
After this conversation I've been thinking about it, and my final
conclusion is that it depends. I find the second solution a better
approach when dealing with small datatypes for the reason I mentioned
above, but when allocating arrays of large structs is probably better the
first one.
Apart of my conclusion, what do you think about it?

No comments:

Post a Comment