+ 13

[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 ... edit 12 sep 2019: <code link removed , adding code in description > #include <stdio.h> int main() { char str1[]="soloquiz"; char str2[]={'s','o','l','o','q','u','i','z'}; printf("%d",sizeof(str1)); printf("%d",sizeof(str2)); return 0; }

6th Apr 2019, 1:18 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
9 Respuestas
+ 11
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
6th Apr 2019, 1:33 PM
Anna
Anna - avatar
+ 9
Great explanation by both of you mods... Anna and Coffee☕Underrun ..Thanks for answering...
6th Apr 2019, 1:37 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 6
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
7th Apr 2019, 2:29 AM
Tavish Nain
Tavish Nain - avatar
+ 4
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.
7th Apr 2019, 4:36 AM
Flying Dutchman
Flying Dutchman - avatar
0
I don't understand the 'return 0' thing... Abt how does it is or becomes 0 or anyother number
16th Apr 2019, 9:26 AM
Sam Winchester
Sam Winchester - avatar
0
I don't understand the 'return 0' thing... Abt how does it is or becomes 0 or anyother number
16th Apr 2019, 9:26 AM
Sam Winchester
Sam Winchester - avatar
0
I had skipped it ....tnx
16th Apr 2019, 10:14 AM
Sam Winchester
Sam Winchester - avatar