我在想,为什么这样行得通
// read n as matrix dimension, then:
int* M;
M = (int*)malloc(n * n * sizeof(int));
// cycle through each "cell" in the matrix and read a number with
scanf("%d", &M[i * n + j]);
这不是吗?
// read n as matrix dimension, then:
int** M;
M = malloc(n * n * sizeof(int));
// cycle through each "cell" in the matrix and read a number with
scanf ("%d", &M[i][j]);
我只是不明白。在这两种情况下,它们都应该是双指针,对吗?
最佳答案
int **
应该指向一个 int*
。在这里你已经分配了一些内存 - 准确地说是 sizeof(int)*rows*cols
字节,然后你使用 M[i]
等。这里 M[i ]
这基本上是 *(M+i)
我们将从 malloc< 返回的一个地址访问
但你分配给 i*sizeof(int*)
偏移量rows*cols
int
而不是 int*
-s - 所以你最终会访问你不应该访问的内存t(通常在 sizeof(int*) > sizeof(int)
的系统上)这将导致您出现未定义的行为。
那怎么解决呢?分配给 int*
-s。
int ** M = malloc(sizeof *M * rows);
if(!M){
perror("malloc");
exit(EXIT_FAILURE);
}
for(size_t i = 0; i < rows; i++){
M[i] = malloc(sizeof *M[i] * cols);
if(!M[i]){
perror("malloc");
exit(EXIT_FAILURE);
}
}
对于您的情况 rows = N
和 cols = N
。
这会给你一个锯齿状的数组,你可以像以前一样访问它。 malloc
负责检查它的返回类型,并在您使用完它后释放内存。这样做。
在第一种情况下,您正在访问分配的内存块,并且您已经使用索引 i
和 j
实现了内存访问,让您自己体验访问内存的方式如果是二维数组,你会这样做。所以在这里使用双指针是没有意义的。你所做的是合法的。
In both cases they should be double pointers
不,他们不应该。第一个与第二个不同。无论如何,它们并不表示同一件事。
关于C - 动态矩阵分配 : something doesn't make sense to me,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48813937/