我想分配一个矩阵。
这是唯一的选择吗:
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 中处理矩阵的首选方法。这是因为现在矩阵将连续存储在内存中,您可以从 locality of reference 中获益。 .基本上,CPU 缓存会对你更满意。
关于c - 在 C 中分配矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128728/