Julian Romero
Julian Romero

Reputation: 41

How do I store a matrix in an array in C?

So I would like to store a couple of matrices in an array. I understand you could make a three dimensional array. What I want to do is to be able to store the matrices I get from AndMatrix method in an array and then use them when I need to. My code is below. arrayOfMatrices variable is a 3 dimensional array I have initialized already. Can someone explain also how I would access these matrices in the array. My code is below:

int** AndMatrix(int **original,int **matA, int **matB, int row, int column){
     int** result=calloc(row, sizeof(int*));
      for (int i = 0; i < row; i++) {
            result[i] = calloc(column, sizeof(int)); }

        return result;}
char temps[10][rows][columns];
arrayOfMatrices[countForMatrices] = AndMatrix(matrix,matrix1, matrix2, rows,columns);

Upvotes: 2

Views: 3434

Answers (1)

dreamcrash
dreamcrash

Reputation: 51403

Declare an array of double pointers :

int **arrayOfMatrices[total_matrices];

or

int ***arrayOfMatrices = malloc(100 * sizeof(int**));

To access the matrices stored in the array, you do it in the same way that you would have done to access a given element from a 1D array, namely:

arrayOfMatrices[0]

to access the matrix stored on the position zero of the array, arrayOfMatrices[1] the accessories the matrix from position one, and so on.

A running example:

#include <stdio.h>
#include <stdlib.h>

int** AndMatrix(int row, int column){
     int** result = calloc(row, sizeof(int*));
     for (int i = 0; i < row; i++) 
            result[i] = calloc(column, sizeof(int)); 
     return result;
}


int main() {
    
    int ***arrayOfMatrices = malloc(sizeof(int**) * 100);
    int row_matrix1 = 10;
    int col_matrix1 = 10;
    arrayOfMatrices[0] = AndMatrix(row_matrix1, col_matrix1);
    int **first_matrix = arrayOfMatrices[0];
    
    // Fill up the matrix with some values
    for(int i = 0; i < row_matrix1; i++)
     for(int j = 0; j < col_matrix1; j++)
         first_matrix[i][j] = i * j;
 
    for(int i = 0; i < row_matrix1; i++){
     for(int j = 0; j < col_matrix1; j++)
         printf("%d ", first_matrix[i][j]);
     printf("\n");
    }
    
    // free the memory accordingly.
    
    return 0;
}
  

Upvotes: 1

Related Questions