6

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?

False Promise
  • 478
  • 3
  • 6
  • 13

4 Answers4

12
#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 
Roby
  • 2,011
  • 4
  • 28
  • 55
6

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

     bool arr[n][m]; 
     for(std::size_t i = 0; i < n; i++){
         for(std::size_t j = 0; j < m; j++){
             arr[i][j]=false;
         }
     }
Kukuster
  • 135
  • 4
  • 10
  • edited to use `std::size_t` (C++ type) instead of `size_t` (C type), which is a better practice in C++ (see https://stackoverflow.com/questions/5813700/difference-between-size-t-and-stdsize-t) – Kukuster Mar 28 '23 at 15:41
0

First thing: Your code worked in my gcc compiler. I don't know why you are getting it wrong.

There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.

Static storage duration in sense is:

An object with static storage duration resides in the same memory address throughout the program's execution.

So, for suppose declaring arr[n][m]={-1} sets only first element to '-1' and others to zero by default. Then also its bad programming style to set arr[n][m]=0.

An better alternative is to use cstring's function memset: memset(arr ,samp, sizeof(arr[0][0]) * m * n); to initialize arr to samp. In your case samp=0.

Update:

As Martin stated it is better not to use memset with multidimensional array. An alternative is use std:fill: std::fill(arr[0], arr[0] + m * n, samp);

This may not be possible in C but possible in C++.

Nihhaar
  • 141
  • 11
  • `memset` should come with heavy warnings. It works for filling integral types, but ***not*** for pointers and floats. `void *p; memset(&p, 0, sizeof(p)); p==nullptr;` is Undefined Behaviour. In practise, I know of no current platform where it won't work, but I have used platforms where it would crash. In other words: `p=0` may mean "set `p` to a null pointer", but that doesn't mean a null pointer is all bits zero. – Martin Bonner supports Monica Aug 21 '16 at 06:53
0

Initialize boolean array from string

Stepping over this question, I present a solution, where the boolean array can be initialized by a string. Thereby '0'=false, '1'=true and ' '=just a spacer. This works similar to the bitset constructor.

Code

#include <iostream>

/**
 * Fills boolean array based on a simple string
 *
 * @param[out] boolean array to be filled
 * @param[in] str accepts only 0 (false), 1 (true) and space (seperator) chars in string
 * @param[in] nMax maximum number of elements to write, -1 is infinite
 * @returns number of writen boolen elements
 */
size_t boolArray_from_string(bool *boolArray, const std::string str, const int nMax = -1)
{
    size_t size = str.size();
    size_t n = 0;
    int cc;
    for (cc = 0; cc < size; cc++)
    {
        if (str.at(cc) == ' ') {continue;}
        if (str.at(cc) != '0' && str.at(cc) != '1') 
        {
            throw std::invalid_argument("str must contain only 0s, 1s and spaces.");
        }
        if (n == nMax)
        {
            throw std::invalid_argument("nMax too small for str content.");
        }

        if (str.at(cc) == '0')
        {
            boolArray[n] = false;
        }
        else
        {
            boolArray[n] = true;
        }
        n++;
    }
    return cc;
}

void print(bool *x, int nRows, int nCols)
{
    for(int row=0; row<nRows; row++)
    {
        for(int col=0; col<nCols; col++)
        {
            std::cout << x[row * nCols + col] << " ";
        }
        std::cout << "\n";
    }
    std::cout << "\n\n";
};

int main()
{
    bool falseArr[3][5];
    boolArray_from_string(&falseArr[0][0], std::string(15, '0'), -1);
    print(&falseArr[0][0], 3, 5);

    bool custArr[3][5];
    boolArray_from_string(&custArr[0][0], "01011 00111 11111", -1);
    print(&custArr[0][0], 3, 5);
}

Output

0 0 0 0 0 
0 0 0 0 0 
0 0 0 0 0 


0 1 0 1 1 
0 0 1 1 1 
1 1 1 1 1 
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58