warez
warez

Reputation: 13

How to do an array of matrix pointers?

I want to create an array of matrix pointers.

int matrix1[4][1] = {
    {1} , 
    {2} ,
    {3} ,
    {4}
};

int matrix2[2][2] = {
    {1, 2} , 
    {3, 4}
};

I'm trying to figure out how to create an array of pointers to call those matrices.

matrix[0][0][0] should return 1 and matrix[1][1][1] should return 4.

So far I've tried this method but I'm getting segmentation fault error.

int *** matrix = (int ***)malloc(2 * sizeof(int **));
matrix[0] = &matrix1;
matrix[1] = &matrix2;

Upvotes: 1

Views: 86

Answers (1)

Aconcagua
Aconcagua

Reputation: 25536

Let's assume 2D arrays first:

int x[2][2];

Type of x[0] now is not int*, it is int[2]. Similarly, &x[0] is not of type int**, but int(*)[2]. You might not have seen that before, it is a pointer to an array of two elements.

If now x decays to a pointer, it decays to exactly the same pointer type (int(*)[2]).

Unfortunatly, pointers to arrays of different size are not compatible (int(*)[10] is unrelated to int(*)[12] – apart from sharing same underlying type). So you won't be able to place them into the same array, unless you use a void* pointer. But you'd lose any information about array sizes, so most likely, it is not the way to go.

I personally would recommend a struct:

typedef struct
{
    size_t rows;
    size_t columns;
    int*   data;
} matrix;

Combined with some helpers:

int get(matrix* m, int r, int c)
{
    return m->data[m->columns * r + c];
}

// perhaps yet setter, constructing and destructing functions?

Structs of this kind you could place into arrays easily...

Upvotes: 1

Related Questions