c - 在 C 中分配矩阵

标签 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));
}

最佳答案

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

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/

相关文章:

json - 使用未按预期工作的指针编辑结构列表变量

c - C中的冒泡排序通用实现

c - 如何让 C 编译器打印\n

python - 在 C 中,如何在没有嵌套函数的情况下为一个函数提供另一个函数的作用域?

linux - socket编程问题ipv6+udp

c - 在 C 中生成随机数

c++用指针反向打印数组内容 - 为什么这种方法有效?

r - 从现有矩阵构建 block 矩阵并在 r 中保留暗名称

r - 按条件对 R 矩阵的行和列进行排序

c++ - 性能问题 : Inverting an array of pointers in-place vs array of values