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.
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.
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
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!
");
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…