'About Null character in C language
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dbush |
