Sunday, July 12, 2009

Please explain to me how to dynamically allocate a 2-D array in C.?

I want to be able to allocate space that can be used as a multi-dimensional array (2-D will do), instead of using C's built in static arrays or infinite arrays.

Please explain to me how to dynamically allocate a 2-D array in C.?
Using standard C, you need to call one of the malloc functions.





For example, if you are allocating a 4 by 3 array of a structurce called THING into a pointer called pThing the code would be -





THING *pThing = malloc (4 * 3 * sizeof (THING));





You can then refer to the THING array just as an other array, to get the 2 element of the third set of THINGs would be -





THING athing = pThings[2][3];





or even -=





THING *pAThing = %26amp;pThings[2][3];





and this is the same thing done with pointer arithmetic -





THING *pAThing = pThings + 2 + (3 * 4);





There is also a function calloc which does the same thing with more parameters -





THING *pThing = calloc (4 * 3, sizeof (THING));





Any memory allocated with malloc or calloc should be released when you are finished with it by calling free -





free (pThing);
Reply:You need to malloc space for both dimensions. So if your array is 5 by 10 you tell malloc to give you enough space for 50 elements.


No comments:

Post a Comment