I\'m reading the C++ Primer Plus by Stephen Prata. He gives this example:
char dog[8] = { \'b\', \'e\', \'a\', \'u\', \'x\', \' \', \'I\', \'I\'}; // not a s
It looks like your C++ compiler is allocating space in 4-byte chunks, so that every object has an address that is a multiple of 4 (the hex addresses in your dump are divisible by 4). Compilers like to do this because they like to make sure larger datatypes such as int
and float
(4 bytes wide) are aligned to 4-byte boundaries. Compilers like to do this because some kinds of computer hardware take longer to load/move/store unaligned int
and float
values.
In your first example, each array need 8 bytes of memory - a char
fills a single byte - so the compiler allocates exactly 8 bytes. In the second example each array is 3 bytes, so the compiler allocates 4 bytes, fills the first 3 bytes with your data, and leaves the 4th byte unused.
Now in this second case it appears the unused byte was filled with a null which explains why cout
stopped at the end of the string. But as others have pointed out, you cannot depend on unused bytes to be initialized to any particular value, so the behaviour of the program cannot be guaranteed.
If you change your sample arrays to have 4 bytes the program will behave as in the first example.