gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:16:34 25 4
gpt4 key购买 nike

我已经尝试了很多次将数组传递给函数然后进行一些计算,例如获取列的总数,问题是我不知道如何从函数中调用结果,通常我会出错.

这只是我昨天尝试解决的一个代码:

#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;
}

这将返回整个矩阵的总和,我假设这就是您所说的获取列的总和

关于c++ - 如何将二维数组传递给函数以及如何调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7551241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com