c - 在设置二维数组的值时出现分段错误,即使循环计数器值在数组的 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;
}
解决方案
你的问题在这里:
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);
}
推荐阅读
- deep-learning - 当我们进行微调任务时,Bert 如何改变最大序列长度?
- c# - Microsoft Entity Framework 不保存更改
- jquery - AngularJS 拆分器示例
- slurm - 排队 SLURM 作业以在 X 分钟后运行
- javascript - 使用 Vue.js 在 Laravel 中上传多张图片
- c# - 带有 asp.net Core Identity 的 Microsoft Identity Pltaform
- nexus - 有没有办法停止更新 Nexus 中的组存储库
- php -
标签不会在谷歌浏览器中显示
- here-api - 如何使用 Routing API 使用 rollup 和 cost_optimize 参数计算成本优化路由?
- deep-learning - 如何在 Tensorflow 2/keras 自定义层中使用基于 numpy 的外部库函数?