首页 > 解决方案 > 在设置二维数组的值时出现分段错误,即使循环计数器值在数组的 sizeof 内

问题描述

我正在声明和打印一个简单的二维数组或矩阵。

我得到一个分段错误,这是由设置矩阵值的嵌套 for 循环引起的。

int rows, columns;
rows = columns = 3;

int **matrix;
matrix = malloc(sizeof(int) * rows);

for (int i = 0; i < columns; i++) {
    matrix[i] = malloc(sizeof(int) * columns);
}

这会引发段错误

for (int i = 0; i < rows; i++) {            
    for (int j = 0; j < columns; j++) {
        matrix[i][j] = 1;
    }
}

如果我设置 i = 1,则没有 seg。过错。

for (int i = 1; i < rows; i++) {            
    for (int j = 0; j < columns; j++) {
        matrix[i][j] = 1;
    }
}

但是,它确实使前 3 个值随机打印。

--------

整个代码

int main(int argc, char const *argv[]) {


int rows, columns;
rows = 3;
columns = 3;

int **matrix;
matrix = malloc(sizeof(int) * rows);

for (int i = 0; i < columns; i++) {
    matrix[i] = malloc(sizeof(int) * columns);
}

for (int i = 0; i < rows; i++) {            
    for (int j = 0; j < columns; j++) {
        matrix[i][j] = 1;
    }
}

for (int i = 0; i < rows; i++) {            
    for (int j = 0; j < columns; j++) {
        matrix[i][j] = 1;
    }
}

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        printf("%d\n", matrix[i][j]);
    }
}

for (int i = 0; i < rows; i++) {
    free(matrix[i]);
}
free(matrix); 

return 1;

}

标签: cmultidimensional-arraysegmentation-fault

解决方案


你的问题在这里:

int **matrix;
matrix = malloc(sizeof(int) * rows);

您想成为一个指向 intmatrix的指针数组,但您使用“sizeof int”而不是“sizeof int 指针”。尝试:

int **matrix;
matrix = malloc(sizeof(int*) * rows);

或更好

int **matrix;
matrix = malloc(rows * sizeof *matrix);

正如@nm 在评论中指出的那样,以下内容:

for (int i = 0; i < columns; i++) {
    matrix[i] = malloc(sizeof(int) * columns);
}

是错的。应为:

for (int i = 0; i < rows; i++) {   // Notice this change
    matrix[i] = malloc(sizeof(int) * columns);
}

推荐阅读