1

I am trying to define a class which takes an input from user and stores it in an array member of class 'Player'

for (i = 0; i < n; i++){
        cout << "Enter scores: ";
        cin >> player1.score[i] >> player2.score[i] ;
        if (player1.score[i] > player2.score[i]) {
            if (player1.highscore < player1.score[i]){
                player1.highscore = player1.score[i] ;
                }
        }

Also here is the class definition

class Player
{
public:
    Player (int n) ;
    int highscore ;
    int score[] ;
};

Player::Player (int n) {
    int i ;
    cout << "Player created" << endl;
    for (i = 0; i < n; i++)
        score[i] = 0 ;
}

Upon running after the program asks for scores, it stops and outputs this number: 132767

Eduard Kim
  • 265
  • 4
  • 15

1 Answers1

0

There are no runtime sized arrays in C++, and int score[] does not magically give you an array of size n.

Use an std::vector<int> score; instead. With that, your constructor will look like this:

Player::Player(int n) : score(n) {
    std::cout << "Player created\n";
}

score will be correctly initialized to 0 and have space for n ints.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182