I have an array, ex:
int M[10] = { 1 };
I expected M[0] ~ M[9] will all be filled with 1, but when I printed them out, it doesn't, only M[0] is 1, others are 0.
I have an array, ex:
int M[10] = { 1 };
I expected M[0] ~ M[9] will all be filled with 1, but when I printed them out, it doesn't, only M[0] is 1, others are 0.
This is a common misconception. Often you see people write things like this
int m[10] = { 0 };
To "initialise all elements to 0
"; however, really that just initialises the first element to 0
and the rest are default initialised (to 0, which is why it works). Really they could've just written int m[10] = {};
You have the same problem: you initialise only the first element to 1
then the rest default to 0
. You can either specify all the parameters, or use std::fill
:
int m[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int n[10];
std::fill(std::begin(n), std::end(n), 1);