【问题标题】:How would I pass a 2d user inputted array from a function into main()?如何将二维用户输入的数组从函数传递到 main()?
【发布时间】:2021-02-26 10:25:07
【问题描述】:

我正在编写一个使用数组的程序,但我不确定如何将二维数组从函数传递到 main()。我想在 main() 中从 read_matrix() 函数的输出数组中设置一个二维数组。

void read_matrix();

int main()
{
    //reads a matrix from user input
    read_matrix();

    new_matrix[][] = matrix[n_i][n_i] //I would like to set a new 2d array in main() from the 2d array
                                      //output from the read_matrix() function.
    return 0;
}


//reads a matrix from user input
void read_matrix()
{
    //initialise variables
    int n_i = 0;
    int row;
    int column;

    //dimensions of matrix
    printf("Enter a value for the dimensions of a square matrix: \n");
    printf(">>");
    scanf("%i", &n_i);

    //initialise matrix
    int matrix[n_i][n_i];

    //elements of matrix
    for(row = 0; row < n_i; ++row)
    {
        for(column = 0; column < n_i; ++column)
        {
            printf("Enter a value for the [%i][%i] element: \n", row, column);
            printf(">>");
            scanf("%i", &matrix[row][column]);
        }
    }

}

【问题讨论】:

  • 请记住,VLA 被认为是一种不好的做法,您应该查看 malloc 和 free。

标签: c function multidimensional-array


【解决方案1】:

你必须在堆上分配你的矩阵,你应该返回它以及它的维度:

int **read_matrix(int *n_i);

int main()
{
    //reads a matrix from user input
    int n_i;
    int **matrix = read_matrix(&n_i);

    //do something 

    free(matrix);

    return 0;
}

//reads a matrix from user input
int **read_matrix(int *n_i)
{
    //initialise variables
    int *n_i = 0;
    int row;
    int column;

    //dimensions of matrix
    printf("Enter a value for the dimensions of a square matrix: \n");
    printf(">>");
    scanf("%i", &n_i);

    //initialise matrix
    int **matrix = malloc(n_i * sizeof(int *));
    for (int i = 0; i < n_i; ++i)
        matrix[i] = malloc(n_i * sizeof(int));

    //elements of matrix
    for(row = 0; row < n_i; ++row)
    {
        for(column = 0; column < n_i; ++column)
        {
            printf("Enter a value for the [%i][%i] element: \n", row, column);
            printf(">>");
            scanf("%i", &matrix[row][column]);
        }
    }

}

【讨论】:

    【解决方案2】:

    你这里有一个大问题。数组在传递或返回给函数时会丢失其长度值。所以你需要返回矩阵的维度和矩阵本身。现在,C 不支持返回两个值。因此,您可以选择将其包装在一个结构中并返回该结构。

    但是,这是一个丑陋的解决方案。此外,由于堆栈的大小限制,您不应该通过值而是使用指针传递/返回值(如矩阵)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-28
      • 2013-02-19
      • 1970-01-01
      • 2010-09-29
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多