+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; }

4/6/2019 1:18:31 PM

🇮🇳Omkar🕉

9 Answers

New Answer

+16

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.

+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

+9

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

+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

+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.

+2

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

0

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

0

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

0

I had skipped it ....tnx