I am learning c. I have the following code:
char s1[] = {'h', 'e', 'l', 'l', 'o'};
char s2[] = {'w', 'o', 'r', 'l', 'd'};
printf("Original strings:nt%snt%sn", s1, s2);
I expect the output to be
Original strings:
hello
world
The output is actually
Original strings:
helloworld
world
It appears that the first array is initialized without a null character ''
at the end, while the second is initialized with a null character. The arrays are also put right next to each other in memory (I print the address, &s1[i]
, along with the value stored there, s1[i]
):
0x7fffe344a98e 104 'h'
0x7fffe344a98f 101 'e'
0x7fffe344a990 108 'l'
0x7fffe344a991 108 'l'
0x7fffe344a992 111 'o'
0x7fffe344a993 119 'w' - not '' ?
0x7fffe344a994 111 'o'
0x7fffe344a995 114 'r'
0x7fffe344a996 108 'l'
0x7fffe344a997 100 'd'
0x7fffe344a998 0 ''
These conditions cause that the printf
function prints helloworld
instead of just hello
for s1
because there is no null character until after ‘d’. If I delete s2
, then s1
does initialize with a null character at the end and prints normally (using %s
). I want to understand why c is deleting the null character after 'o'
in s1
when I declare a second char array immediately after.
I can specify the size of both arrays (for instance, s1[6] = {'h', ...}
), and my issue is resolved. However, I don’t understand why c is deleting the null character in s1
, or just never placing it in memory, when I create two char arrays sequentially. Thank you.