c - 将多维数组传递给 C 中的函数时出现段错误

标签 c macos segmentation-fault

我们在介绍中看到了使用指针将数组传递给函数。到 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/

相关文章:

c - OpenCV 使用带有灰度图像的 cvImageCreate() 失败,并且调整大小通常失败

无法从用户读取字符

创建流程生成器

python - _tkinter TclError : can't find package Tix

c++ - 关于 std::stack push 段错误的问题

c++ - 以相反的顺序存储整数值

objective-c - EXC_BAD_ACCESS 调用 block

macos - 错误 : Unable to 'pub upgrade' flutter tool. 五秒后重试...(还剩 9 次尝试)

linux - 信号处理程序中的 pthread_exit 导致段错误

c - 在循环中调用 strtok() 时出现段错误