在 C 中分配矩阵 [英] allocate matrix in C

查看:34
本文介绍了在 C 中分配矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分配一个矩阵.

这是唯一的选择吗:

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

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

推荐答案

嗯,你没有给我们一个完整的实现.我猜你是这个意思.

Well, you didn't give us a complete implementation. I assume that you meant.

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 缓存会对你更满意.

One of these two options is actually the preferred way of handling a matrix in C. This is because now the matrix will be stored contiguously in memory and you benefit from locality of reference. Basically, the CPU cache will a lot happier with you.

这篇关于在 C 中分配矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆