繁体   English   中英

将多维数组传递给C中的函数时的分段错误

[英]Segmentation fault in passing multidimensional arrays to functions in C

在我的简介中,我们看到了使用指针将数组传递给函数的信息。 到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[rows][cols]的地址在&matrix[rows][cols]的末尾。

矩阵的第一个元素是&matrix[0][0] ,矩阵的最后一个元素是&matrix[rows-1][cols-1]

另外,这个声明

void fillMatrix();

将导致与此定义有关的问题:

void fillMatrix( int *matrix, int rows, int cols ){
    ...

他们需要匹配。 现在,由于最上面的void fillMatrix()声明,参数通过默认参数提升被传递给函数,但是由于定义具有显式参数,因此函数本身希望将参数作为int *int传递。 您可能对此没有任何问题,因为这些参数的默认值可能与那些参数相同,但函数定义和声明通常必须完全匹配。

我尚未检查您的代码是否存在其他问题。

在C中,当您声明数组时,需要在编译时指定其大小。 当您使阵列减速时

    int matrix[rows][cols];

您实际上是使用垃圾值来初始化其大小的。 对于我的编译器,它的大小为[0] [0]初始化。 为了实现您想要的目标,您需要执行以下两项操作之一:

  1. 在编译之前明确指定数组的大小
  2. 为数组动态分配空间

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM