I'm working on a C program, which requires me to access and store matrices of different sizes (2d arrays) for future operations. I'm considering using either an array of pointers to matrices, or an array of matrices.
I found a couple of answers provided here and here that were helpful. Ideally, though, I would like to know a solution that doesn't require dynamic allocation (see code below), and still uses arrays.
(The results I found focused mainly on initialisation of the array. I would like to understand more about this of course, but also more about storing/accessing a matrix).
For example, I would like to create a matrix (e.g. arr[2][2]
and arr[5[6]
(different sizes)) and then store/access them when needed. I have written a test code for this, but I get an error for the second part.
CODE
int main()
{
int** arr1 = calloc(10, sizeof(int*));
for (int i = 0; i < 10; i++)
arr1[i] = calloc(10, sizeof(int));
/* creating simple 2x2 matrix
(in fact, filling part of the 10x10 matrix dynamically allocated) */
arr1[0][0] = 1; arr1[0][1] = 2; arr1[1][0] = 3; arr1[1][1] = 4;
int ***arrayOfMatrices = malloc(sizeof(int**) * 100);
arrayOfMatrices[0] = arr1;
printf("%d\n",arrayOfMatrices[0][1][0]); //outputs 3 as expected
/* 3x3 matrix */
int arr2[3][3];
arr2[0][0] = 5; arr2[0][1] = 6; arr2[1][0] = 7; arr2[1][1] = 8;
arrayOfMatrices[1] = arr2;
printf("%d\n",arrayOfMatrices[1][1][0]);
//test.c:38:24: error: assignment to ‘int **’ from incompatible pointer type ‘int (*)[3]’ [-Werror=incompatible-pointer-types]
return 0;
}
What is the best way to do store matrices? Are there any alternatives to this approach?