I am trying to create a class called Player which has an array called scores, declared with a size in the Player class properties. Yet, when I initialize a new player, the sizeof(scores) method is giving me 20, and, does, in fact, initialize a score array of size 20 as opposed to 5. I am wondering why and how to fix this. Here is the code and output.
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
struct stats {
unsigned int min;
unsigned int max;
unsigned int mode;
unsigned int modeFreq;
unsigned int mean;
unsigned int total;
};
class Player {
public:
int scores[5];
stats pStats;
void inputScores();
void calculateStats();
void printScores();
};
void Player::printScores(){
cout << "Printing Scores..." << endl;
for (int i = 0; i < sizeof(scores); i++) {
cout << scores[i] << endl;
}
}
void Player::inputScores(){
for (int i = 0; i < sizeof(scores); i++) {
cout << "Enter a score for [" << i << "]: ";
int input;
cin >> input;
scores[i] = input;
}
}
int main() {
Player p;
cout << sizeof(p.scores);
p.inputScores();
p.printScores();
}
Which gives me this:
20
Enter a score for [0]: 1
Enter a score for [1]: 2
Enter a score for [2]: 3
Enter a score for [3]: 4
Enter a score for [4]: 5
Enter a score for [5]: 6
Enter a score for [6]: 7
Enter a score for [7]: 8
Enter a score for [8]: 20
Enter a score for [0]: 1
Enter a score for [1]: 2
Enter a score for [2]: 3
Enter a score for [3]: 4
Enter a score for [4]: 5
Enter a score for [5]: 6
Enter a score for [6]: 7
Enter a score for [7]: 8
Enter a score for [8]:
....
So on, up to 20...