+ 2
The compiler adds a null to the end of the literal, "hello"+'\0', not to your array. It will not forcibly overwrite the end of your array with a null. If the array size is insufficient for the entire literal, then the literal gets truncated and your array is left without a terminating null. So any operation that relies on finding a terminating null will iterate through memory without regard to the end of the declared array until it finds some memory location that holds a null.
It is educational to observe what happens if you swap the lines of your array declarations.
#include <stdio.h>
int main() {
char str2[ ] = "world"; /* size 6 */
char str1[5] = "hello";
printf("str1 is: %s, str2 is: %s", str1, str2);
return 0;
}
Output:
str1 is: helloworld, str2 is: world
In this case, the next null that printf finds after str1 is at the end of str2.
+ 2
When you declare str1 the null character is automatically put at the end of the string, being "hello\0", but you specified the length of 5, taking only the first 5 characters of the passed string ("hello"), cutting out the null character. Now, the use of the null character is to tell the output functions (e.g. printf()) where the string ends, so without it printf() would print garbage characters (took from memory) until it finds a null character. Here explained your random output.
+ 2
The SoloLearn memory management is the reverse of what you expected. Hello could vanish or worldhello might happened. It depends on the order the compile puts them into the data block likely: world\0ello. Variables on the stack start high and go lower.
+ 1
vipul jain yes, you understand it correctly