-4
#include <stdio.h>

int main() {
    char str3[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
    char str4[ ] = {'h', 'e', 'l', 'l', 'o'}; 
    printf("%s, %s", str3, str4);
    
    return 0;
}

The output for this is : hello, hellohello

Why two times hello ????

2 Answers2

1

str4 has no 0-terminator, so printf keeps reading out of bounds of the array and by luck (or not) there seems to be str3 directly behind str4, so it reads till the 0-terminator of str3.

In the end ==> undefined behavior, don't rely on that.

mch
  • 9,424
  • 2
  • 28
  • 42
0

str4 does not contain a null terminator. Since str4 and str3 are sequentially allocated on the stack by the compiler, the second %s in the printf will start printing str4 and due to the lack of a null terminator continue with printing str3.