by jotux · 8y ago · 0 comments
You can even do sparse initialization if we're talking C99 here, like so:
int array[] = {1, 2, 3, [99] = -1}
And you'll get an array of length 100 {1, 2, 3, 0, 0, 0, ..., 0, -1}
Any missing initialized element is always 0 if initialization is done at all, though.
But I agree that it would make sense to fill the array (or have an easier method to do that), it may just be an argument of speed. I think OSes generally hand over uninitialized memory zero'ed out to prevent reading of memory from previous programs - so it's a case of allocating the memory space and then continuing, as opposed to setting values for each position.
int array[5] = {X};
Could be be used to set all values of the array to X, but have never used it for anything other than 0. That's somewhat surprising behavior.> int array[5] = { 0 };
which takes advantage of this missing element initialization behaviour.