Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

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?

like image 787
Fabricio Avatar asked Dec 12 '22 22:12

Fabricio


1 Answers

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.

like image 53
Daniel Fischer Avatar answered May 24 '23 08:05

Daniel Fischer