Intainer Intainer - 3 months ago 30
C++ Question

C++ boolean array initialization

I want to initilize all elements from my 2-dimensional boolean array to false.

size_t n, m;
cin >> n >> m;
bool arr[n][m] = {false};
for(size_t i = 0; i < n; i++){
for(size_t j = 0; j < m; j++){
cout << arr[i][j] << " ";
}
cout << endl;
}


But i'm getting very confused with the output. For example, if n = 5 and m = 5, i have the following :

0 27 64 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0


So, what's wrong with the code?

Answer

Initialize the values with a for structure, exactly as how you print it

     bool arr[n][m]; 
     for(size_t i = 0; i < n; i++){
         for(size_t j = 0; j < m; j++){
             arr[i][j]=false;
         }
     }