Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ array initialization not working

Tags:

c++

arrays

gcc

I am trying to initialize an array of bools like so:

bool FcpNumberIsOk[MAX_FCPS]={true};

but when I debug it, I only see the first element of the array initialized, the others are false. How can that be so? I am using Qt on ubuntu 10 and the initialization is done on a local array inside a method.

Ok thanks for your answers.

like image 943
yan bellavance Avatar asked Aug 30 '10 18:08

yan bellavance


People also ask

Does C initialize arrays to 0?

Initialize Arrays in C/C++ c. The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

What happens if an array element is not initialized in C?

If we use any uninitialized array in C program, compiler will not generate any compilation and execution error i.e. program will compile and execute properly. If the array is uninitialized while declaring and even after the declaration if you do not initialize then, you may get unpredictable result.

What happen if automatic array is not initialized?

If the array is not initialized at the time of declaration or any time after that then it will contain some random values in each memory position.


1 Answers

You've misunderstood. It appears that you though that any unmentioned elements would get initialized to the same value as the last explicitly initialized value. The last value you mentioned was true, so all further elements would be initialized to true as well. I once had that same belief, but I quickly learned otherwise.

That's not how it works. Any unmentioned elements get default-initialized, which for bool means false.

To set all the elements to true, try something like std::fill_n:

std::fill_n(FcpNumberIsOk, MAX_FCPS, true);
like image 150
Rob Kennedy Avatar answered Oct 04 '22 12:10

Rob Kennedy