Home > Blockchain >  Newbie: Are defined strings set to all NULLs?
Newbie: Are defined strings set to all NULLs?

Time:04-15

I am trying to remember my brief C experiences from five years ago.

I could have sworn that I read that a string that was defined but not initialized was set to all NULLs. In other words, that

char string[10];

consisted of 10 null characters, and that

char string[10] = "Kevin";

consists of the letters 'K', 'e', 'v', 'i', 'n' and five nulls.

Is this true:

  1. Always?
  2. Sometimes, depending on the compiler?
  3. Never?

CodePudding user response:

in other words, that char string[10]; consisted of 10 null characters,

That depends where and on the variable.

char here_yes[10]; // 10 '\0' characters
int main() {
    char here_no[10]; // 10 unknown garbage values
    static char but_here_also_yes[10]; // also 10 '\0' characters
}

and that char string[10] = "Kevin"; consists of the letters 'K', 'e', 'v', 'i', 'n' and five nulls. Is this true: Always?

Yes. If you partially initialize a string or a variable, the rest is filled with '\0' or zeros.

char this_has_10_nulls[10] = "";
int main() {
    char this_has_ab_followed_by_8_nulls[10] = { 'a', 'b' };
    static char this_has_Kevin_followed_by_5_nulls[10] = "Kevin";
}

CodePudding user response:

If there is no initializer present (as in your first example), then all elements of the array will have indeterminate values. From this C11 Draft Standard:

6.7.9 Initialization


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

However, if you provide any sort of initializer (as in your second example), then any elements in the array that aren't explicitly set will be initialized to zero. From a few paragraphs later in the Standard:

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.

(Note that a char of static storage duration will be initialized to zero.)

  • Related