PDA

View Full Version : 2d arrays



Mungo
04-24-2004, 08:58 AM
I need to implement a 2D array of a variable size but i dont know how to malloc 2d arrays anyone know how??

thanks for any help.

Andrew Davey
04-24-2004, 10:58 AM
try this link, not sure if it will help havent looked in a long time:

http://www.iota-six.co.uk/c/f7_dynamic_memory_allocation.asp

miko
04-27-2004, 07:36 AM
for example you want array of floats


int arrayheight = 666;
int arraywidth = 5;
int i;
float **array;

array = (float**)malloc(sizeof(float*) * arrayheight);
if(*array == NULL) {
fprintf(stderr,"not enought memory! buy a better machine!\n");
exit(1);
}

for(i=0;i<arrayheight;i++) {
array[i] = (float*)malloc(sizeof(float) * arraywidth);
//TODO: check if malloc was succesful;-)
}

/* ...do something with array... */

for(i=0;i<arrayheight;i++)
free(array[i]);

free(array);

/* we are done!!! let's buy another beer :)*/should work...