如何将二维数组传递给函数以及如何调用它
How to pass two dimensions array to a function and how to call it
我已经尝试了很多时间将数组传递给函数,然后做一些计算,例如获得列的总数,问题是我不知道如何调用函数的结果,通常我会得到错误。
这只是一个代码,我试图解决它从昨天:
#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
给它,在后一种情况下你不能合法地遍历整个多维数组。考虑不要使用数组,这样更简单。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 函数何时会在c++中包含stack_Unwind_Resume调用
- Singleton模式中的手动析构函数调用:调用多次
- 从同一父调用调用不同的子类函数
- 我可以通过CPP程序中的数据库调用调用Java程序
- C++17标准对在nullptr上调用delete有何规定
- NSIS系统::调用-调用方法失败
- 参数构造函数调用调用
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- 让非托管 C++ 代码调用调用 C# 代码的托管 C++ 代码
- 关于在矢量上调用clear如何改变容量,标准有何规定
- 如何让函数调用调用它的函数
- 如何p/调用调用函数只使用,但c++需要.a/.lib/.o文件
- C#DLL可以调用调用本机C++静态库的C++/CLI托管包装器吗