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

I have a problem with the project. I have to make a variable size 2D array to store some prediction error. This applies to images. The problem is that I have to upload images of different sizes, so for each image I would have to get a 2D array with the appropriate number of pixels in the file. I searched among your questions, but that is not what I am looking for. Can anybody help me?

thanks

+7
source share
4 answers

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

unsigned arr[n][m]; 

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

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

and later

 free(arr); 
+6
source

If you need contiguous memory, you have several options.

You can dynamically allocate one block of memory, and then calculate your offsets manually, for example:

 size_t rows, cols; ... int *arr = malloc(sizeof *arr * rows * cols); ... arr[i * rows + j] = ...; // logically equivalent to arr[i][j] 

You can configure the second array of pointers into the main array:

 int **arrp = malloc(sizeof *arrp * rows); ... for (i = 0; i < rows; i++) arrp[i] = &arr[i * rows]; ... arrp[i][j] = ...; 

remembering that you would need to free both arr and arrp .

If you have a C99 implementation, you can simply set the pointer to VLA, for example:

 int (*arrp)[cols] = (int (*)[cols]) arr; ... arrp[i][j] = ...; 

Note that in this case you do not allocate any memory for the secondary array, and you do not need to manually calculate the pointers in the main array; all you have to do is set arrp to the same place as arr and let the pointer arithmetic rules do all the work.

If the images are not so large, you can simply configure the VLA (again, C99 or later):

 int arr[rows][cols]; 

but in practice this is not a good idea; stack frames are usually quite limited in size.

+2
source

You need to allocate memory dynamically. Use double pointer logic.

Example:

 int n=10; <<-u can change this. int **a; a=(int **)malloc(sizeof(*int)*n); for (int i=0;i<n;i++){ a[i]=(int *)malloc(sizeof(int)*n);// or *(a+i) } 
0
source

As an example, consider allocating a 2D int array:

 int **array1 = (int**) malloc (nrows *sizeof(int*)); for (int i=0; i<nrows;i++) array1[i]=(int*) malloc (ncols *sizeof(int)); 

where nrows → no rows ncols → no columns const or # define

0
source

All Articles