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.
John bode
source share