I am trying to understand how character arrays are initialized and how are the data stored.
I did a test and this is how it goes
struct test
{
char one [2];
char two [2];
char three[2];
};
test * testptr;
char testchar[] = "hello";
testptr = reinterpret_cast<test*>(testchar);
cout << testptr->one << endl;
cout << testptr->two << endl;
cout << testptr->three << endl;
I was expecting to see something like:
he
ll
o
However, when i complile, I get:
hello
llo
o
I do not understand how is one
and two
contains more character than the size itself, when i do a sizeof
for the variables, they all turn out to be 2
, just as the size it was initialized.
And if a cout
like this is done:
for (int i = 0; i < 6; i++)
{
cout << testptr->one[i] << endl;
}
The result is:
h
e
l
l
o
If i go more than 6
, it would be either empty or rubbish.
I know i can use memcpy
to allocate nicely the amount bytes into the array, but i'm trying to understand how does a fixed size character array, able to store more that what it can hold.
When you reinterpret_cast
the char[]
to struct*
, the pointers to one
, two
and three
point to the 0th, 2nd, and 4th character respectively in the input string (with a gap of two since the size of each variable is two, so something like ptr
, ptr + 2
, ptr + 2 + 2
).
h e l l o
^ ^ ^
| | |
0 2 4
Also, a char*
in C++ is terminated by a NULL character ('\0'
). Hence, when you print the value of one
, two
and three
, we see all the characters from the beginning until the end is encountered.