在C中分配矩阵
我想分配一个矩阵。
这是唯一的选择吗:
int** mat = (int**)malloc(rows * sizeof(int*))
for (int index=0;index<row;++index)
{
mat[index] = (int*)malloc(col * sizeof(int));
}
i want to allocate a matrix.
is this the only option:
int** mat = (int**)malloc(rows * sizeof(int*))
for (int index=0;index<row;++index)
{
mat[index] = (int*)malloc(col * sizeof(int));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好吧,你没有给我们一个完整的实现。我想你的意思是。
这是另一种选择:
来模拟矩阵
然后,使用行主要排序和
列主要排序
。这两个选项之一实际上是在 C 中处理矩阵的首选方法。这是因为现在矩阵将连续存储在内存中,并且您可以受益于 引用位置。基本上,CPU 缓存会对你更满意。
Well, you didn't give us a complete implementation. I assume that you meant.
Here's another option:
Then, you simulate the matrix using
for row-major ordering and
for column-major ordering.
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.
其他答案已经涵盖了这些内容,但为了完整起见,comp.lang.c FAQ 有一个相关条目:
如何动态分配多维数组?
The other answers already covered these, but for completeness, the comp.lang.c FAQ has a relevant entry:
How can I dynamically allocate a multidimensional array?
你可以做的是
然后使用这个新矩阵作为 mat[i][j]
what you can do is
and then use this new matrix as mat[i][j]
您还可以使用 calloc,它还会为您对矩阵进行零初始化。签名略有不同:
You may also use calloc, which will additionally zero initialize the matrix for you. The signature is slightly different:
怎么样:
How about just:
您可以将其折叠为对 malloc 的一次调用,但如果您想使用二维数组样式,则仍然需要 for 循环。
未经测试,但你明白了。否则,我会坚持杰森的建议。
You can collapse it to one call to malloc, but if you want to use a 2d array style, you still need the for loop.
Untested, but you get the idea. Otherwise, I'd stick with what Jason suggests.