[英]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.
我想要做的是能够将我从 AndMatrix 方法获得的矩阵存储在一个数组中,然后在需要时使用它们。 My code is below.
我的代码如下。 arrayOfMatrices variable is a 3 dimensional array I have initialized already.
arrayOfMatrices 变量是我已经初始化的 3 维数组。 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);
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:要访问存储在数组中的矩阵,您的操作方式与访问一
1D
数组中的给定元素的方式相同,即:
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.要访问存储在 position 零的数组的矩阵,
arrayOfMatrices[1]
的附件从 position 的矩阵一,依此类推。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.