How to declare a variable size 2D array in C?

astefan picture astefan · Feb 21, 2012 · Viewed 15k times · Source

I have a problem with a project. I have to make a variable size 2D array for storing some prediction error..so this is about images. The trouble is that I have to load images of different sizes so for each image I would have to get into a file the 2D array with the coresponding number of pixels..I've searched among your questions but it's not what I'm looking for.Can anyone help me?

Thank you

Answer

Jens Gustedt picture Jens Gustedt · Feb 21, 2012

If you have a modern C compiler (at least C99) in function scope it is as simple as:

unsigned arr[n][m];

this is called a variable length array (VLA). It may have problems if the array is too large. So if you have large images you could do:

unsigned (*arr)[m] = malloc(sizeof(unsigned[n][m]));

and later

free(arr);