开发者

C++ array initialization not working

开发者 https://www.devze.com 2023-01-14 05:47 出处:网络
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 th

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.


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);


Because that's the way array initialization works in C++. If you don't explicitly give a value for each element, that element defaults to zero (or, here, false)

 bool FcpNumberIsOk[MAX_FCPS]={true, true, true, true /* etc */ };

Note that

 bool FcpNumberIsOk[MAX_FCPS];

Will set all values to false or have them set randomly, depending on where this is defined.


This is expected behaviour. The first element is initialized to the specified value and the remainder are initialized to the default value of 0:

int c[5] = {1};

// 1 0 0 0 0
for(int i = 0; i < 5; ++i)
  std::cout << c[i] << ' ';


Because you have explicitly initialized only the first element of the array, only the first element is initialized and the remaining are not.


Using this syntax you are only initializing the first element (with your's value and other get default-one [false]), but not others. You should use either int array and memset or for loop to initialize all elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消