Fabricio
Fabricio

Reputation: 7935

Is a char array initialized with zeros/null after string end, when there's still space left?

Consider the following char array:

char str[128] = "abcd";

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

Upvotes: 4

Views: 1346

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183978

Yes, if there are fewer elements explicitly given in an initialiser than the aggregate contains, then the remaining elements are initialised as if the aggregate had static storage duration. For integer types (and char is one) that means with 0s. The relevant section of the standard is 6.7.9 (21):

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

String literals as initialisers for char arrays are equivalent to brace-encloded initialisers in that respect.

Upvotes: 10

Kerrek SB
Kerrek SB

Reputation: 477512

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

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

Missing array elements are zero-initialized, hence the remainder of the array is all zeros.

Upvotes: 3

Related Questions