在C中分配矩阵

我想分配一个矩阵。

这是唯一的选择:

int** mat = (int**)malloc(rows * sizeof(int*)) for (int index=0;index<row;++index) { mat[index] = (int*)malloc(col * sizeof(int)); } 

好吧,你没有给我们一个完整的实现。 我认为你的意思。

 int **mat = (int **)malloc(rows * sizeof(int*)); for(int i = 0; i < rows; i++) mat[i] = (int *)malloc(cols * sizeof(int)); 

这是另一种选择:

 int *mat = (int *)malloc(rows * cols * sizeof(int)); 

然后,使用模拟矩阵

 int offset = i * cols + j; // now mat[offset] corresponds to m(i, j) 

对于行主要排序和

 int offset = i + rows * j; // not mat[offset] corresponds to m(i, j) 

用于列主要排序。

这两个选项中的一个实际上是在C中处理矩阵的首选方法。这是因为现在矩阵将连续存储在内存中,并且您可以从引用的局部性中受益。 基本上,CPU缓存会让你更开心。

其他答案已经涵盖了这些,但为了完整起见,comp.lang.c FAQ有一个相关的条目:

如何动态分配多维数组?

你能做的是

 int (*mat)[col]; mat=(int (*)[col])malloc(sizeof(*mat)*row); 

然后使用这个新矩阵作为mat [i] [j]

怎么样:

 int* mat = malloc(rows * columns * sizeof(int)); 

您也可以使用calloc,它会为您初始化矩阵。 签名略有不同:

 int *mat = (int *)calloc(rows * cols, sizeof(int)); 

可以将其折叠为对malloc的一次调用,但如果要使用二维数组样式,则仍需要for循环。

 int** matrix = (int*)malloc(rows * cols * sizeof(int) + rows * sizeof(int*)); for (int i = 0; i < rows; i++) { matrix[i] = matrix + rows * sizeof(int*) + rows * cols * sizeof(int) * i; } 

未经测试,但你明白了。 否则,我会坚持杰森的建议。

对于N维数组,您可以这样做:

 int *matrix = malloc(D1 * D2 * .. * Dn * sizeof(int)); // Di = Size of dimension i 

要使用典型方式访问arrays单元,您可以执行以下操作:

 int index = 0; int curmul = 1; int i; int indexes = {I1, I2, ..., In}; // Ii = Index in dimension i for(i = N-1; i >= 0; i--) { index = index + indexes(i) * curmul; curmul = curmul * Di; } 

(注意:现在没有测试但应该工作。从我的Matlab代码翻译,但在Matlab索引从1开始,所以我可能犯了一个错误(但我不这么认为))

玩得开心!