Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of elements of a character array initialized as an empty string

Suppose the following initialization:

char mystr[4] = "";

Does the C99 standard guarantee that a character array initialized to an empty string will initialize all elements in the character array to null bytes? For example, does the standard guarantee that mystr[2] == '\0'?

How about these initializations:

char myfoo[4] = { '\0' };
char mybar[4] = { 0 };

While I'm pretty certain that explicitly setting the first element of a character array will guarantee the implicit initialization of the rest of the elements to 0, I suspect a string literal initialization results in a copy to the array -- thus meaning a single \0 is copied to the array while the remaining elements are left uninitialized.

like image 832
Vilhelm Gray Avatar asked Jun 06 '13 21:06

Vilhelm Gray


1 Answers

Section 6.7.8, paragraph 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.

And how are objects with static storage duration initialized?

Section 6.7.8, paragraph 10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

char is an arithmetic type, so it's initialized to 0. Huzzah, you can rest easy.

like image 169
Taylor Brandstetter Avatar answered Oct 27 '22 16:10

Taylor Brandstetter