1

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
rid
  • 61,078
  • 31
  • 152
  • 193
chibiw3n
  • 357
  • 2
  • 15
  • Your "double loop" is printing elements of the array, not initialising them. The array of `int`s has automatic storage duration, so is uninitialised. Accessing the value of uninitialised variables (or, in your case, uninitialised array elements) causes undefined behaviour. – Peter Jun 19 '20 at 01:48

1 Answers1

3

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.

Eric Backus
  • 1,614
  • 1
  • 12
  • 29
  • 4
    No need for `std::fill`, you can just use the initialiser. – Konrad Rudolph Jun 18 '20 at 22:02
  • Caveat on that first paragraph: POD variable in some circumstances, for example if `arr` was global, [are initialized for you](https://stackoverflow.com/questions/2218254/variable-initialization-in-c). – user4581301 Jun 18 '20 at 22:12
  • 1
    "The uninitialized values can be anything, can even be different from one run of your program to the next." - Don't even assume that there is a value. Reading uninitialized memory is undefined behavior, so you can get a lot more than just a random value. Serious security vulnerabilities have been caused by developers assuming that uninitialized values are just "garbage". – eesiraed Jun 18 '20 at 22:41
  • using `std::fill` on a 2-D array is a bit awkward – M.M Jun 18 '20 at 23:06