Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Newbie: Are defined strings set to all NULLs?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading