c++ passing 2d arrays to funcions

痴心易碎 提交于 2019-12-02 11:06:20

问题


I know my code isnt finished yet im not asking for it to be done. It's supposed to input food eaten by 3 monkeys over a week and other stuff. But I've hit a snag. It gives me an error(Error: no operator "<<" matches these operands) when i put the cin in the poundsEaten function. Am I not passing the array right is that why it isnt working? Thanks for any help

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

回答1:


You've declared array as containing const doubles. They're constant, so you can't write to them as you are trying to do with cin >> array[index][count];. Just change the parameter declaration to:

double array[][DAYS]

Perhaps you should think about when and why you should declare a variable as const.

As an aside to avoid later confusion, it's worth mentioning here that there's no such thing as array type parameters. The above parameter is actually transformed to:

double (*array)[DAYS]

However, your code is written appropriately to work with this (you passed the number of rows to the function).




回答2:


you declare:

const double array[][DAYS],

however, inside poundsEaten function, you are asking user to input information to fill in the array, which means the array is not const, therefore, error. Remove the const qualifier from the parameter such that the array can be changed by user input.

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

BTW: don't use array as variable name for an array, use some other names for good practice. Meanwhile,cols is not used inside your poundsEaten function.



来源:https://stackoverflow.com/questions/15908496/c-passing-2d-arrays-to-funcions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!