【发布时间】:2019-04-20 04:42:17
【问题描述】:
我们在介绍中看到使用指针将数组传递给函数。到 C 类,我正在尝试学习如何自己传递多维数组。我尝试编写一个函数来将矩阵条目的值分配给本地数组,但出现分段错误。我希望有人能解释为什么会发生这种情况以及如何解决它。我在 macOS Sierra 上使用终端。提前致谢。我的代码如下:
#include <stdio.h>
#include <stdlib.h>
void fillMatrix();
int main(void){
int rows, cols;
printf("\nEnter the number of columns:\n");
scanf("%d", &cols);
printf("\nEnter the number of rows:\n");
scanf("%d", &rows);
int matrix[rows][cols];
fillMatrix(&matrix[rows][cols], rows, cols);
for (int i = 0; i < rows; ++i){
for (int j = 0; j < (cols - 1); ++j){
printf("%d ", matrix[i][j]);
} printf("%d\n", matrix[i][(cols -1)]);
}
return 0;
}
void fillMatrix( int *matrix, int rows, int cols ){
for (int i = 0; i < rows; ++i){
for (int j = 0; j < cols; ++j){
printf("\nPlease enter the A(%d,%d) entry:\n", i, j);
scanf("%d", &*(matrix + (i*cols) + j));
}
}
return;
}
【问题讨论】:
标签: c macos segmentation-fault