【问题标题】:Passing 2D array to a function without using vectors [duplicate]将二维数组传递给函数而不使用向量[重复]
【发布时间】:2021-04-01 09:08:38
【问题描述】:

我正在编写一个程序,以二维数组的形式打印用户输入的方阵元素的总和,而不使用向量。但是我收到 2 个错误:

  • 错误 1:error:array has incomplete element type 'int []'

  • 错误 2: error: expected expression cout<<sumarr(arr[][]

这是我的程序:

int sumarr(int arr[][])                 // ERROR 1
{
    // finging no. pf rows(or coloums) of the square matrix
    int n = sizeof(arr) / (2 * sizeof(int));
    int sum = 0;
    for (int i = 0; i < n; i++)         // calculating sum of elements
    {
        for (int j = 0; j < n; j++)
        {
            sum += arr[i][j];
        }
    }
}
int main()
{
    int n;                            // No. of rows(or coloumns) of the square matrix
    cin >> n;
    int arr[n][n];
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)   // inputting array elements
        {
            cin >> arr[i][j];
        }
    }
    cout << sumarr(arr[][]);          // ERROR 2
    return 0;
}

有人可以建议我为什么会收到这些错误以及如何解决这些错误吗?

【问题讨论】:

    标签: c++ multidimensional-array


    【解决方案1】:

    在函数参数(错误 1)中,您至少需要指定数组的最后一个维度:

    int sumarr(int arr[][SIZE]){ /*...*/}
    

    在调用函数时只需要使用数组名,不需要解引用(错误2):

    cout << sumarr(arr);
    

    问题就变成了Variable Length Arrays are not allowed in C++,所以你可能应该重新考虑使用向量来完成这项任务的可能性。

    另外值得一提的是,函数内部的sizeof(arr) 不会为您呈现数组的大小,而是指针的大小which is what arr becomes when passed as an argument

    或者,您可以手动为数组分配内存,它或多或少看起来像这样:

    Live sample

    #include <iostream>
    #include <cassert>
    
    // since sizeof arr can't work you should pass the size as argument
    int sumarr(int **arr, int n) 
    {
        assert(n > 0 && n < 1000); // confirm that n is valid, > 0 and a suitable upper limit
        
        int sum = 0;
        for (int i = 0; i < n; i++) //calculating sum of elements
        {
            for (int j = 0; j < n; j++)
            {
                // input and sum in the same loop will save you a O(N^2) operation
                std::cin >> arr[i][j];
                sum += arr[i][j];
            }       
        }
        return sum;
    }
    
    int main()
    {
        int n; //No. of rows(or columns) of the square matrix
        std::cin >> n;
    
        // memory allocation for 2D array
        int **arr = new int *[n];
        for (int i = 0; i < n; i++)
        {
            arr[i] = new int[n];
        }
        //end
        
        int sum = sumarr(arr, n); // passing array and size
        std::cout << "Sum: " << sum;
         
        // freeing memory after use
        for (int i = 0; i < n; i++)
        {
            delete [] arr[i];
        }
        delete [] arr;
        //end
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 2013-05-12
      • 2018-09-11
      • 2013-01-18
      • 2021-07-15
      • 2013-03-28
      • 1970-01-01
      • 2020-11-01
      相关资源
      最近更新 更多