0

I am trying to understand how can I initialize a bool array, I tried using memset and it worked but, when I tried to initialize it directly I failed.

bool prime[n+1] ;
memset(prime,true,sizeof(prime));

-- this works.

but the following doesn't.

bool prime[n+1] = {1};
//memset(prime,true,sizeof(prime));

I've tried the following too.

bool prime[n+1] = {1};
Bonzo
  • 427
  • 2
  • 10
  • 28
  • 4
    Possible duplicate of [How to initialize all members of an array to the same value?](https://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value) – Alan Birtles Sep 10 '19 at 13:48
  • In case n in your sample is a variable and not a constant this isn't really "legal" c++ in terms of following the c++ standard. Array initialization based on a variable only works on some compilers or in some cases only with compiler extensions so you should probably avoid doing that. If you want a dynamic array use std::vector instead. – Eric Sep 10 '19 at 14:42

2 Answers2

4

It does initialize your array. This is how brace-enclosed initialization works. The first array element is initialized to 1, which translates to true, and all other elements are initialized to 0 which translates to false. This:

bool v[10] = { 1 };

is the same as if you had:

bool v[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

You can use the std::fill function and friends:

std::fill(std::begin(v), std::end(v), true);
std::fill_n(v, 10, true);
Ron
  • 14,674
  • 4
  • 34
  • 47
1

Initializing an array like this:

bool foo[10] = {1};  // initialize only the first element to 1, the rest get 0.

You need to use the memset approach, or else provide n values in your initializer list

bool foo[10] = {1,1,1,1,1,1,1,1,1,1};

Or use std::fill, a loop, or any other way to set all the values.

Chris Uzdavinis
  • 6,022
  • 9
  • 16