gpt4 book ai didi

c - 在 C 中分配矩阵

转载 作者:太空狗 更新时间:2023-10-29 16:36:55 25 4
gpt4 key购买 nike

我想分配一个矩阵。

这是唯一的选择吗:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com