如何将二维数组传递给函数以及如何调用它

How to pass two dimensions array to a function and how to call it

本文关键字:何调用 调用 函数 二维数组      更新时间:2023-10-16

我已经尝试了很多时间将数组传递给函数,然后做一些计算,例如获得列的总数,问题是我不知道如何调用函数的结果,通常我会得到错误。

这只是一个代码,我试图解决它从昨天:

#include <iostream>
using namespace std;
//prototype
int get_total(int whatever[][2], int row);
int main ()
{
    const int row=2;
    const int col=3;
    int marks[row][col];
    // this is prompt the user to input the values
    for (int i=0; i<row;i++)
    {
        for (int p=0; p<col; p++)
        {
            cin >> marks[i][p];
        }
        cout << endl;
    }
    // this is just display what the user input as a table
    for (int x=0; x< row ; x++)
    {
        for (int y=0; y<col ; y++)
        {
            cout << marks[x][y] << "  ";
        }
        cout << endl;
    }
    int sum;
    // this is the most important thing I want to know,
    // how to call the function :(
    sum=get_total(marks,row);
    return 0;
}
// to get the total of each columns
const int row=3;
// not sure if the declaration is correct or not :(
int get_total(int whatever[][2], int row)
{
    for (int i=0; i < 2; i++)
    {
        for (int p=0; p < 3; p++)
            int total=0;
        //this line is completly wrong, How can I calculate the total of columns?
        total+=get_total[2][p];
    }
    // do we write return total ?
    // I'm not sure because we need the total for each column
    return total;
}

很抱歉混乱,我感谢任何帮助解释将多维数组作为参数传递给函数以及如何调用函数>

调用函数时数组衰变成指针。

你可以做两件事:

  • 将行数和列数作为参数传递给函数。

  • 使用std::vector代替。我建议你看一看,它会奏效的,你会学到一些新的、非常有用的东西。

同样,你的函数应该这样做:

int get_total(int** whatever)
{
    //total is 0 at the beginning 
    int total=0;
    for (int i=0; i < 2; i++)
    {
        for (int p=0; p < 3; p++)
            //go through each element and add it to the total
            total+=whatever[i][p];
    }    
    return total;
}

这将返回整个矩阵的总数,我假设这就是您所说的getting the total of the columns

int marks[row][col]

表示marks的类型为int[2][3]

int get_total(int whatever[][2], int row);

你已经声明get_total接受int(*)[2]int[2][3]可以衰减到int(*)[3],但这与int(*)[2]不兼容,因此为什么不能将marks传递给get_total。你可以声明get_total来接受int(*)[3]:

int get_total(int whatever[][3], int row);
// equivalent to:
int get_total(int (*whatever)[3], int row);

如果你决定声明get_total接受int**int*,那么在前一种情况下你不能合法地传递marks给它,在后一种情况下你不能合法地遍历整个多维数组。考虑不要使用数组,这样更简单。