Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 243
astefan Avatar asked Feb 21 '12 16:02

astefan


People also ask

How do you declare the size of a 2D array?

We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.

How do you declare a 2D array with variables?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.

Can you declare an array with a variable size in C?

Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.

How do you pass a 2D array of variable size in a function?

We can pass the 2D array as an argument to the function in C in two ways; by passing the entire array as an argument, or passing the array as a dynamic pointer to the function.


1 Answers

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);
like image 146
Jens Gustedt Avatar answered Oct 02 '22 10:10

Jens Gustedt