我们在介绍中看到了使用指针将数组传递给函数。到 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;
}
最佳答案
鉴于声明
int matrix[rows][cols];
这段代码是错误的:
fillMatrix(&matrix[rows][cols], rows, cols);
&matrix[行][列]
的地址超出了矩阵末尾。
矩阵的第一个元素是&matrix[0][0]
,矩阵的最后一个元素是&matrix[rows-1][cols-1]
>.
此外,此声明
void fillMatrix();
此定义会导致问题:
void fillMatrix( int *matrix, int rows, int cols ){
...
他们需要匹配。现在,由于顶部的 void fillMatrix()
声明,参数通过 default argument promotion 传递给函数。 ,但由于定义具有显式参数,因此函数本身期望参数以int *
或int
形式传递。您可能不会遇到问题,因为这些参数的默认值可能与这些参数相同,但函数定义和声明通常必须完全匹配。
我还没有检查您的代码是否存在其他问题。
关于c - 将多维数组传递给 C 中的函数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347241/