c++将2d数组传递给函数

c++ passing 2d arrays to funcions

本文关键字:函数 数组 2d c++      更新时间:2023-10-16

我知道我的代码还没有完成,但我并没有要求它完成。它应该输入3只猴子一周吃的食物和其他东西。但是我遇到了一个障碍。它给了我一个错误(错误:没有操作符"<<"匹配这些操作数),当我把cin放在poundsEaten函数。我没有正确传递数组这就是为什么它不能工作吗?谢谢你的帮助

#include <iomanip>
#include <iostream>
using namespace std;
//Global Constants
const int NUM_MONKEYS = 3;
const int DAYS = 7;
//Prototypes
void poundsEaten(const double[][DAYS],int, int);
void averageEaten();
void least();
void most();
int main()
{
    //const int NUM_MONKEYS = 3;
    //const int DAYS = 7;
    double foodEaten[NUM_MONKEYS][DAYS]; //Array with 3 rows, 7 columns
    poundsEaten(foodEaten, NUM_MONKEYS, DAYS);
    system("pause");
    return 0;
}
void poundsEaten(const double array[][DAYS], int rows, int cols)
{
    for(int index = 0; index < rows; index++)
    {
        for(int count = 0; count < DAYS; count++)
        {
            cout << "Pounds of food eaten on day " << (index + 1);
            cout << " by monkey " << (count + 1);
            cin >> array[index][count];
            // Here is where i get the error
        }
    } 
}

您已经声明array包含const double s。它们是常数,所以你不能像写cin >> array[index][count];那样写它们。只需将参数声明更改为:

double array[][DAYS]

也许您应该考虑何时以及为什么应该将变量声明为const

为了避免以后的混淆,这里值得一提的是,没有数组类型参数这样的东西。上面的参数实际上被转换为:
double (*array)[DAYS]

但是,您的代码被适当地编写以处理此问题(您将row s的数量传递给函数)。

您声明:

const double array[][DAYS],

然而,在poundsEaten函数中,你要求用户输入信息来填充array,这意味着array不是const,因此,错误。从参数中删除const限定符,以便array可以通过用户输入更改。

void poundsEaten(double array[][DAYS], int rows, int cols)

BTW:不要使用array作为数组的变量名,请使用其他名称。同时,cols不能在poundsEaten函数中使用。