Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value of dynamic array

This code will create an array of 100 elements and set the value of each to false.

bool boolArray[100] = false;

How can I set the default value of a dynamic array?

void Foo(int size)
{
    bool boolArray = new bool[size];
    //Now what?
}
like image 764
peace_within_reach Avatar asked Nov 24 '10 02:11

peace_within_reach


3 Answers

In standard C++ you can default-initialize just about anything, including that array:

bool* boolArray = new bool[size]();     // Zero-initialized

Complete program that also checks the result, and deallocates the array:

bool foo( int size )
{
    bool* boolArray = new bool[size]();     // Zero-initialized

    // Check that it is indeed zero-initialized:   
    for( int i = 0; i < size; ++i )
    {
        if( boolArray[i] ) { delete[] boolArray; return false; }
    }
    delete[] boolArray; return true;
}

#include <iostream>
int main()
{
    using namespace std;
    cout << (foo( 42 )? "OK" : "Ungood compiler") << endl;
}

Whether your compiler will accept or even do the Right Thing is another matter.

So, in practice, if you feel an irresistible urge to use a raw array, then perhaps better use std::fill or some such, or even a raw loop.

But note the repeated delete[]-expressions. Such redundant code is very easy to get wrong: it's Evil™. And there's much else that can go wrong with use of raw arrays, so as a novice, just Say No™ to raw arrays and raw pointers and such.

Instead, use standard library containers, which manage allocation, initialization, copying and deallocation for you – correctly. There is a little problem with that, though, namely a premature optimization in std::vector<bool>, which otherwise would be the natural choice. Essentially std::vector<bool> uses just one bit per value, so that it can't hand out references to bool elements, but instead hands out proxy objects…

So, for bool elements, use e.g. a std::bitset (when the size is known at compile time), or e.g. a std::deque, as follows:

#include <deque>

bool foo( int size )
{
    std::deque<bool> boolArray( size );     // Zero-initialized

    for( int i = 0; i < size; ++i )
    {
        if( boolArray[i] ) { return false; }
    }
    return true;
}

#include <iostream>
int main()
{
    using namespace std;
    cout << (foo( 42 )? "OK" : "Ungood compiler") << endl;
}

Cheers & hth.,

like image 169
Cheers and hth. - Alf Avatar answered Nov 20 '22 15:11

Cheers and hth. - Alf


Use std::fill function or std::fill_n function.

std::fill_n(boolArray, length, defaultValue);
std::fill(boolArray, boolArray + length, defaultValue);

Side note: try using std::vector instead.

like image 29
mmx Avatar answered Nov 20 '22 13:11

mmx


bool* boolArray = new bool[size];
for(int i = 0; i < size; i++) {
    boolArray[i] = false;
}
like image 45
ThiefMaster Avatar answered Nov 20 '22 14:11

ThiefMaster