Hacker News new | past | comments | ask | show | jobs | submit login

Why doesn't the {1} in this case initialize the array to all 1s?



Spec defines any remaining elements to be initialized to 0.

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.


It's because you can initialize the array with particular values, like: `type a[3] = { 1 , 2, 3 };`.

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.


Until now, I always thought this:

    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.


Because that's not how array initialisation works in C. The specified indices are initialised with the provided values, and the missing elements are always initialised to 0. See for instance section 6.7.9 of the C99 standard. Perhaps you were confused by the common idiom:

> int array[5] = { 0 };

which takes advantage of this missing element initialization behaviour.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: