开发者

Having trouble passing array to function

I am getting all kinds of errors when passing my array to this function. The function is suppose to have the user enter a name and a score and store them in 2 seperate arrays, one for the names, one for the scores. I believe I have to use pointers but have no idea on how to use them. I don't want the answer, just a push in the right direction. Here is the code:

#include <iostream>

int InputData(int &, char, int);

using namespace std;

int main()
{
    char playerName[100][20];
    int score[100];
    int numPlayers = 0;

    InputData(num开发者_开发问答Players, playerName, score);
    return 0;
}

int InputData(int &numPlayers, char playerName[][20], int score[])
{
    while (numPlayers <= 100)
    {
        cout << "Enter Player Name (Q to quit): ";
        cin.getline(playerName, 100, ‘\n’);
        if ((playerName[numPlayers] = 'Q') || (playerName[numPlayers] = 'q'))
        return 0;
        cout << "Enter score for " << playerName[numPlayers] <<": ";
        cin >> score[numPlayers];
        numPlayers++;
    }
}

Ok, I made some more changes and the errors are less, must be getting close, Lol!


This looks like a school assignment and I applaud you for not asking for the answer. There are several ways to do it, but you are already fairly close in the approach that you are using. When you pass an array reference, you do not want to include the length of the array. For example, the parameter int score[100] should be int score[]. The exception, especially in your scenario, is with multidimensional arrays. In this case, you want to use char playerName[][20]. Your function declaration also needs to change to match. Don't forget InputData returns an int. Your declarations and function call are correct; you just need to adjust your function signature.


Keeping the errors aside -

InputData(numPlayers, playerName, score, size);
                                      // ^^^^ size is no where declared
                                      // resulting Undeclared indentifier error

Prototype mentions of taking 3 arguments but calling the function passing 4 parameters.

Hint regarding errors:

  • An 1D array decays to a pointer pointing to first element in the array while passing to a function.
  • A 2D array decays to a pointer pointing to the 1D array ( i.e., T[][size] ) while passing to a function.
  • Return type of main() should be int.

It seems with the given hints you corrected most of the errors. But you forgot to change the prototype. So, change -

int InputData(int &, char, int);

to

int InputData(int &, char[][20], int[]);

Why aren't you using std::string array for player names ? Use it and remove rest of the errors. Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜