首页 > 解决方案 > 如何将矩阵存储在C中的数组中?

问题描述

所以我想在一个数组中存储几个矩阵。我知道你可以制作一个三维数组。我想要做的是能够将我从 AndMatrix 方法获得的矩阵存储在一个数组中,然后在需要时使用它们。我的代码如下。arrayOfMatrices 变量是我已经初始化的 3 维数组。有人可以解释一下我将如何访问数组中的这些矩阵。我的代码如下:

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);

标签: arrayscmatrixmultidimensional-array

解决方案


声明一个双指针数组:

int **arrayOfMatrices[total_matrices];

或者

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

要访问存储在数组中的矩阵,您的操作方式与访问1D数组中给定元素的方式相同,即:

arrayOfMatrices[0]

访问存储在数组位置零的arrayOfMatrices[1]矩阵,从位置一开始的矩阵的附件,依此类推。

一个运行的例子:

#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;
}
  

推荐阅读