用C分配矩阵 [英] allocate matrix in C
本文介绍了用C分配矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想分配矩阵。
这是唯一的选择:
INT **垫=(INT **)的malloc(行*的sizeof(INT *))对于(INT指数= 0;指数 - LT;排++指数)
{
垫[指数] =(INT *)malloc的(COL *的sizeof(INT));
}
解决方案
好吧,你没有给我们一个完整的实现。我假设你的意思。
INT **垫=(INT **)的malloc(行*的sizeof(INT *));
的for(int i = 0; I<行;我++)垫[I] =(INT *)malloc的(COLS *的sizeof(INT));
下面是另一种选择:
为int *垫=(INT *)malloc的(行* COLS *的sizeof(INT));
然后,您使用模拟矩阵
INT偏移= I * COLS + J;
//现在垫[偏移]对应于M(I,J)
有关行为主的顺序以及
INT偏移= I +行*焦耳;
//没有垫[偏移]对应于M(I,J)
有关列主顺序。
一这两个选项其实是在处理C.矩阵中的preferred方式这是因为现在的矩阵将在内存中连续存放,并从你的的wikipedia.org/wiki/Locality_of_reference\">locality。基本上,CPU缓存会更快乐了很多你。
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));
}
解决方案
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));
Here's another option:
int *mat = (int *)malloc(rows * cols * sizeof(int));
Then, you simulate the matrix using
int offset = i * cols + j;
// now mat[offset] corresponds to m(i, j)
for row-major ordering and
int offset = i + rows * j;
// not mat[offset] corresponds to m(i, j)
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.
这篇关于用C分配矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文