Dynamic memory allocation

Started by
2 comments, last by WildWest 20 years, 8 months ago
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!
The Wild Wild West - Desperado!
Advertisement
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
"Absorb what is useful, reject what is useless, and add what is specifically your own." - Lee Jun Fan
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 = malloc(sizeof(int) * 5);<br>}<br><br>… and Bob's your father's brother!<br><hr height=1 noshade></SPAN></BLOCKQUOTE><br><br>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<br><br>int *array_of_array[5] = malloc(5 * sizeof *array_of_arrays);<br><br>Now you have a 5x5 array of arrays.<br><br><BLOCKQUOTE><SPAN CLASS=smallfont>quote:<hr HEIGHT=1 noshade><br>(Naturally, replace the int with whatever data type you are dealing with - and don't forget to free it all up in reverse order).<br><hr height=1 noshade></SPAN></BLOCKQUOTE><br><br>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 &#111;nly &#111;ne block of memory.<br><br>EDIT: "fixed" subscript <br><br><SPAN CLASS=editedby>[edited by - Way Walker on July 28, 2003 12:00:19 PM]</SPAN>
malloc returns a void pointer, you need an int pointer in that instance
OpenGL Revolutions http://students.hightechhigh.org/~jjensen/

This topic is closed to new replies.

Advertisement