arrays - 如何将矩阵存储在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);
解决方案
声明一个双指针数组:
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;
}
推荐阅读
- c - 我想从文件输入创建一个 BST
- r - 对数据框中的组执行多个fisher.test
- dynamic-scope - 基于动态范围查找值
- python - 如何在 QSortFilterProxyModel 更新上更新 QLabel
- android - IllegalStateException:在 Jetpack Compose 测试期间未初始化 FocusRequester
- flutter - 任何想法如何删除此错误“空值检查运算符用于空值”
- css - (LESS 语言)无序列表的每个级别的不同文本颜色/大小 | 最小行高 | 最小边距,填充
- memory-leaks - Xamarin.IOS 内存泄漏 - 监控内存消耗?
- c# - 如何使用 JWT 令牌授权用户对 asp net core web api 做出反应。何时使用自动化标头不记名令牌?
- javascript - 如何使用按钮将文本输入保存并显示到本地存储