0

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?

D-I-S-C
  • 79
  • 1
  • 6
  • I think the error tells it all. You are attempting to assign a pointer to an array of 3 ints (`'int (*)[3]'`) to a pointer to a pointer of ints (`'int **'`). The compiler won't let you do this. The problem here (with C) is that you need to be explicit about all the memory you allocate and free and there is no robust built in technique for growing memory. There is `realloc` but when you are doing arrays of arrays this can get tricky. I don't know about **best** practices, but when I was a C programmer I would usually stick to types of ** for 2D arrays and be really careful. – dmedine Jan 12 '22 at 01:40

1 Answers1

1

What about something like this for pointer to an array?

int main()
{
    int m3[4][5][6];
    int (*ptom3)[5][6] = m3;
    m3[1][1][1] = 27;
    printf("%d\n",((ptom3)[1][1][1]));//prints 27 as expected
    return 0;
}
Irelia
  • 3,407
  • 2
  • 10
  • 31