Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
False Promise Avatar asked Dec 06 '22 17:12

False Promise


2 Answers

#include <iostream>

template<int N>
void print(bool x[N][N] )
{
    for(int i=0; i<N; i++)
    {
        for(int j=0; j<N;j++)
            std::cout << x[i][j] << " ";
        std::cout << "\n";
    }
    std::cout << "\n\n";
};

int main()
{
    bool a[10][10];
    bool b[10][10]{};


    print(a);
    print(b);

  return 0;
}

prints:

./main 
120 29 96 0 0 0 0 0 131 10 
64 0 0 0 0 0 168 161 188 139 
4 127 0 0 255 255 0 0 1 0 
0 0 0 176 40 152 253 127 0 0 
153 10 64 0 0 0 0 0 2 0 
0 0 0 0 0 0 221 11 64 0 
0 0 0 0 65 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
144 11 64 0 0 0 0 0 160 8 
64 0 0 0 0 0 32 177 40 152 


0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
like image 151
Roby Avatar answered Dec 11 '22 11:12

Roby


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;
         }
     }
like image 30
Ricardo Ortega Magaña Avatar answered Dec 11 '22 11:12

Ricardo Ortega Magaña