<分区>
int **twoDary = (int**) (malloc(rows * sizeof(int *)));
int **twoDaryStart = twoDary;
int *currentrow;
for ( i = 0; i < rows; i++ ){ // Originally: for (i = 0; i < columns; i++)
*(twoDary + i) = (malloc(columns * sizeof(int)));
}
for (j = 0; j < rows; j++) {
currentrow = *(twoDary + j);
for ( i = 0; i < columns; i++ ) {
*(currentrow + i) = i;
printf("%d\n", *(currentrow+i));
}
}
我正在尝试创建一个动态二维数组。然后我试图将 i ,当前 i (在内部 for 循环中)分配给每一行中的每个元素。所以我的输出应该是数字 0 - 列打印的行时间。
如果我的行和列不相同,即 5 行 10 列,我会不断收到段错误。谁能从这段代码中看出为什么会发生这种情况?
你的第一个循环应该是:
for (i = 0; i < rows; i++)
{
...
}
显然代码是一致的(但错误)——同样的问题出现在 free()
代码中。这是我的 SSCCE对于这个问题。 valgrind
给它一份干净的健康证明.
#include <stdlib.h>
#include <stdio.h>
extern int **alloc_array(int rows, int columns);
int **alloc_array(int rows, int columns)
{
int i;
int j;
int **twoDary = (int**) (malloc(rows * sizeof(int *)));
int **twoDaryStart = twoDary;
int *currentrow;
for ( i = 0; i < rows; i++ ){
*(twoDary + i) = (malloc(columns * sizeof(int)));
}
for (j = 0; j < rows; j++) {
currentrow = *(twoDary + j);
for ( i = 0; i < columns; i++ ) {
*(currentrow + i) = i;
printf("%d\n", *(currentrow+i));
}
}
return twoDary;
}
int main(void)
{
int **d2 = alloc_array(5, 10);
for (int i = 0; i < 5; i++)
free(d2[i]);
free(d2);
return(0);
}