[SOLVED] Question about string in C.

I have initialized two strings with same values using 2 different methods.....I was expecting sizeof both strings to be 10 because there are 9 characters in each of those strings... and one more byte for NULL char \0 but one string is having size 9.. So my question is why that string doesn't require extra one byte for null on the other hand first string needs it? Please answer.. Thanks in advance 😇 https://code.sololearn.com/cXFp8veV32uY/?ref=app

4/6/2019 1:18:31 PM


9 Answers

New Answer


With a string literal, the compiler appends \0 for you. With the second one, you are just initializing an array that happens to be characters. The compiler does not automatically append to arrays initialized this way. You need to add the \0 in that case or you may run into issues if the data following that array in memory isn't a \0.


char str1[]="soloquiz"; This defines an array of chars and automatically adds the null character at the end, so the length is 9. With char str2[]={'s','o','l','o','q','u','i','z'}, you define the char array yourself and since you don't end it with a null character, you won't be able to use it properly. If you try this: printf("%s\n", str2); , the output is more than "soloquiz" because it will print everything that is in memory until it first meets a null character. So you might get an output like soloquizgfdbjjhzrdssrzt556778ijhjk


Great explanation by both of you mods... Anna and Coffee☕Underrun ..Thanks for answering...


This is because null char \0 is only added at the end of the string literal but not at the end of the character array. So when you initialise a string as a character array the size comes 9


Try to display not sizes, but strings: printf("%s\n",str1);//1 case printf("%s\n",str2);//2 case In the first case, the output will be correct. In the second case, printing will continue beyond the array to the first encountered 0.


Sam Winchester https://www.sololearn.com/learn/C/2911/


I don't understand the 'return 0' thing... Abt how does it is or becomes 0 or anyother number


I don't understand the 'return 0' thing... Abt how does it is or becomes 0 or anyother number


I had skipped it ....tnx