在C中分配矩阵

时间:2010-01-24 20:43:16

标签: c pointers matrix malloc

我想分配一个矩阵。

这是唯一的选择:

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

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

7 个答案:

答案 0 :(得分:27)

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

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中处理矩阵的首选方法。这是因为现在矩阵将连续存储在内存中,您将从locality of reference中受益。基本上,CPU缓存对你来说会更快乐。

答案 1 :(得分:6)

其他答案已经涵盖了这些,但为了完整起见,comp.lang.c常见问题解答中有相关条目:

How can I dynamically allocate a multidimensional array?

答案 2 :(得分:4)

你可以做的是

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

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

答案 3 :(得分:2)

如何:

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

答案 4 :(得分:2)

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

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

答案 5 :(得分:0)

可以将其折叠为对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;
}

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

答案 6 :(得分:-1)

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

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

要使用典型方式访问阵列单元格,您可以执行此操作:

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开始,所以我可能犯了一个错误(但我不这么认为))

玩得开心!

相关问题