Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are defined strings set to all NULLs?

Tags:

c

c-strings

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?
like image 779
Kevin Zembower Avatar asked Feb 10 '26 23:02

Kevin Zembower


1 Answers

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";
}
like image 199
KamilCuk Avatar answered Feb 13 '26 13:02

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!