How is an array stored in memory in this program?
First notice that your program is undefined behavior as you call printf
with a char array and not a string since there isn't room for the zero-termination in the two arrays. For instance you only reserve 5 chars for a
and world
takes up all 5, i.e. no room for the termination.
A strict person would say that due to UB it makes no sense to speculate about what is going on - with UB anything can happen.
But if we do it anyway then it is likely as described below.
The answer would depend on your system as c
doesn't specify all aspects of storing data. It is specified that an array must be in contiguous memory but exactly how and where that memory is located, is beyond the standard.
From the output you have, it seems that your system have located it like this:
haii how are youworld
^ ^
b a
You can't know what is after the last d
.
However, when you print a
you get the output world
which tells us that "by luck" there is a '\0' just after the last d
.
haii how are youworld'\0'
^ ^ ^
b a "luck"
So printing a
will give world
and printing b
will give haii how are youworld
.
Your code should be:
char a[6] = "world";
char b[17] = "haii how are you";
to make room for the termination of each string and so that your memory layout would be
haii how are you'\0'world'\0'
^ ^
b a
Notice: The '\0' that you got "by luck" is probably because your system initializes all memory assigned to your program to zero at start up.