Archived

This topic is now archived and is closed to further replies.

WildWest

Dynamic memory allocation

Recommended Posts

Hi! Can I allocate memory dynamically for multidimension-arrays using straigt C ? I am only able to allocate a one-dimension array via malloc. I do not get the clue how to do it for multi-dimension arrays. Anybody ideas? The Wild Wild West - Desperado!

Share this post


Link to post
Share on other sites
Yes indeedy - if you allocate a single-dimension array already you are half way there....

If you want an array that is 5x5, the first thing is to allocate enough memory for 5 pointers:

array_of_arrays = malloc(sizeof(int *) * 5);

... then allocate each 2nd dimension array:

for (int i = 0; i < 5; i++) {
array_of_arrays = malloc(sizeof(int) * 5);
}

... and Bob''s your father''s brother!

(Naturally, replace the int with whatever data type you are dealing with - and don''t forget to free it all up in reverse order).




"Absorb what is useful, reject what is useless, and add what is specifically your own." - Lee Jun Fan

Share this post


Link to post
Share on other sites
quote:
Original post by JY
Yes indeedy - if you allocate a single-dimension array already you are half way there....

If you want an array that is 5x5, the first thing is to allocate enough memory for 5 pointers:

array_of_arrays = malloc(sizeof(int *) * 5);

... then allocate each 2nd dimension array:

for (int i = 0; i < 5; i++) {
array_of_arrays[ i ] = malloc(sizeof(int) * 5);
}

... and Bob's your father's brother!



What you've done is make an array of pointers to the first element of arrays. If you want a true multi-dimensional array (i.e. an array of arrays) you'd have to do something like

int *array_of_array[5] = malloc(5 * sizeof *array_of_arrays);

Now you have a 5x5 array of arrays.

quote:

(Naturally, replace the int with whatever data type you are dealing with - and don't forget to free it all up in reverse order).



Note that the way shown above has neither of these problems. You don't have to worry about replacing the int in the malloc call because the type isn't hardcoded in there. You don't have to worry about freeing it in reverse order because there's only one block of memory.

EDIT: "fixed" subscript

[edited by - Way Walker on July 28, 2003 12:00:19 PM]

Share this post


Link to post
Share on other sites