Array starting with 16 in the first element.

Hello everyone. I'm working on an assignment for my computer science class and I can't for the life of me figure out why my array has the number 16 in the first index.

My goal with this function is for the user to enter the command "N" followed by a number to add a number to the array. The code I have for this works, however it changes the 16 added by default to a 10 and display it at the end of the array. When tested without putting in any numbers, the 16 is there by default. What do I need to change in my code to avoid this? Thanks for any help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
void statsArray()
{
    char command;

    int sum = 0;
    int arraySize = 1;

    int statsArray[arraySize];
    bool exit = false;

    do
    {
        cin >> command;

        switch(command)
        {
            case 'N' :
                cin >> statsArray[arraySize - 1];
                cin.clear();
                cin.ignore();
                cout << "OK" << endl;
                arraySize++;
                break;
            case 'S' :
                for(int i = 0; i < arraySize; i++)
                    sum += statsArray[i];
                cout << sum << endl;
                break;
            case 'D' :
                for(int i = 0; i < arraySize; i++)
                    cout << statsArray[i] << " ";
                break;
        }
    } while(!exit);


}


When nothing is entered into the array and the command "D" is entered:

D
16


When N 1 and N 2 are entered by the user and then "D" is entered:

N 1
OK
N 2
OK
D
1 2 10
1
2
3
4
5
int arraySize = 1;

int statsArray[arraySize];

arraySize++;

The size of an array must be known at compile time, so the size of an array is constant. In this case, the array will only have a size of 1. When you try to access the array with an index greater than arraySize - 1, you aren't actually accessing what's stored in the array, but some junk values next to the array in memory. As a result, your program will not run as expected and usually crash. You just got lucky, and didn't crash.

If you want to have a variable sized array, I'd recommend using a vector.
http://www.cplusplus.com/reference/vector/vector/
Thank you for your reply! Unfortunately, we haven't gone over vectors in class yet, so I can't use them. I did however, based on your response, create a fixed sized frequency array that I'm toying around with.

Again, thanks for your reply!
Topic archived. No new replies allowed.