2

This is my program: Click link to see the program In this program,

char c[5] = "hello\0world";

When I print the string c using the following line:

printf("\nstring c=%s", c);

It gives the following output (with smile symbol at the end, not exactly like the symbol below, but I can say it is a smiley symbol:

string c=hello(•‿•)

Why doesn't it print hello In the output? because the size of string is only 5?

Thanks in advance.

chqrlie
  • 131,814
  • 10
  • 121
  • 189

1 Answers1

2

The array c is only 5 characters wide, and the initializer given has too many characters for an array that size. So only the first 5 characters of the string constant are used to initialize the array.

This means that the array contains only the characters 'h', 'e', 'l', 'l', and 'o'. In other words, you don't have a string because it's not null terminated. So printf ends up reading past the end of the array triggering undefined behavior.

If you omit the array size:

char c[]="hello\0world";

It will be made large enough to fit the entire initializer. Then printf will print "hello" since it will stop reading at the null byte.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • I have a question.here the size of char c is 5. So should it not store only four characters i.e."hell" and a null character "\0" at the end? –  Feb 28 '22 at 07:35
  • @Heli_Aghara No, because that's not what it's being initialized with. A `char` array doesn't necessarily have to hold a null-terminated string. – dbush Feb 28 '22 at 12:42
  • So, if we don't add a Null character in this case i.e. char c[5]="hello\0world" ,it is not a string bt just a character array.right? –  Feb 28 '22 at 13:21
  • @Heli_Aghara Yes, the null terminator is what makes it a string. – dbush Feb 28 '22 at 13:22