Is char array initialized with zeros / zero after the end of a line, when there is still a space?

Consider the following char array:

char str[128] = "abcd"; 

Are all remaining uninitialized characters in the rest of the array (from str[4] to str[127] ) filled with zero / zero?

+4
source share
2 answers

Yes, if the initializer clearly indicates fewer elements than the collection contains, then the remaining elements are initialized as if the collection had a static storage duration. For integer types (and char is one), which means 0s. The relevant section of the standard is 6.7.9 (21):

If the list enclosed in curly brackets contains fewer initializers than elements or elements of the population or fewer characters in the string literal used to initialize an array of known sizes than there are elements in the array, the rest of the population must be initialized implicitly in the same way as objects having a static storage duration.

String literals as initializers for char arrays are equivalent to encoded initializers in this regard.

+10
source

Yes, the string literal initializer is identical to the following initializer:

 char str[128] = { 'a', 'b', 'c', 'd', 0 }; 

Missing elements of the array are initialized to zero, so the rest of the array is all zeros.

+3
source

Source: https://habr.com/ru/post/1432126/


All Articles