Search code examples
c++arraysvectorinitializationint

Why is my double array not initializing to 0?


I am creating a 2-D array. However, when I use a double for-loop to check the contents of my 2-D array, it is filled with random numbers. I know that I can use a double for-loop to manually fill my double array with 0's. However, I am confused on why it does not do this when it is initialized.

int arr[5][5];
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        cout << arr[i][j]  << " ";
    }
    cout << endl;
}

output:

0 0 0 0 0 
0 0 0 -272632592 32766 
-272632616 32766 0 1 0 
0 0 0 0 0 
0 0 0 0 -272632608 
Program ended with exit code: 0

Solution

  • In C and C++, variables of POD (plain old data) types, and arrays of such types, are normally not initialized unless you explicitly initialize them. The uninitialized values can be anything, can even be different from one run of your program to the next. You will have to initialize them yourself.

    There are cases where POD types are automatically initialized (for example if arr were global it would be zero initialized) but it is usually good practice to initialize POD types even in those cases.

    You could use std::fill() or std::fill_n() to fill your array, which would allow you to avoid writing a double for loop.

    Instead, you could use std::vector<int> to hold your 2-D array. This is guaranteed to initialize the values in the array. You could also consider std::vector<std::vector<int>> to emphasize the 2-D nature of your data, but it will probably be less convenient.