I have the following code:
# include <iostream>
using std::cout;
const int ARRAY_SIZE = 15;
union one4all
{
int int_value;
long long_value;
double double_value;
char char_value[ARRAY_SIZE];
};
int main()
{
one4all x;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
x.char_value[i] = (int)(i + 97);
}
cout << x.char_value << '\n';
system("pause");
}
This code was printing gibberish after the last character value. Then, after some research it says that the reason is because it cannot detect a terminating character and hence, it keeps on printing.
https://i.stack.imgur.com/7MFvS.png
So, I updated my code to this:
# include <iostream>
using std::cout;
const int ARRAY_SIZE = 15;
union one4all
{
int int_value;
long long_value;
double double_value;
char char_value[ARRAY_SIZE];
};
int main()
{
one4all x;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
x.char_value[i] = (int)(i + 97);
}
x.char_value[ARRAY_SIZE - 1] = '\0';
cout << x.char_value << '\n';
system("pause");
}
This worked perfectly because it has a terminating character at the end.
https://i.stack.imgur.com/WVsBB.png
This raised questions: