jas*_*son 28
好吧,你没有给我们一个完整的实现.我认为你的意思.
int **mat = (int **)malloc(rows * sizeof(int*));
for(int i = 0; i < rows; i++) mat[i] = (int *)malloc(cols * sizeof(int));
Run Code Online (Sandbox Code Playgroud)
这是另一种选择:
int *mat = (int *)malloc(rows * cols * sizeof(int));
Run Code Online (Sandbox Code Playgroud)
然后,使用模拟矩阵
int offset = i * cols + j;
// now mat[offset] corresponds to m(i, j)
Run Code Online (Sandbox Code Playgroud)
用于行主要排序和
int offset = i + rows * j;
// not mat[offset] corresponds to m(i, j)
Run Code Online (Sandbox Code Playgroud)
用于列主要排序.
这两个选项中的一个实际上是在C中处理矩阵的首选方法.这是因为现在矩阵将连续存储在内存中,并且您将受益于引用的局部性.基本上,CPU缓存会让你更开心.
小智 5
你能做的是
int (*mat)[col];
mat=(int (*)[col])malloc(sizeof(*mat)*row);
Run Code Online (Sandbox Code Playgroud)
然后使用这个新矩阵作为 mat[i][j]