Extremely simple code with output I don't understand...
#include <iostream>
using namespace std;
int main() {
char text1[] = {'v', 'e', 'r', 'y'};
cout << text1 << endl;
char text2[] = "strange";
cout << text2 << endl;
return 0;
}
For some reason I get this output:
very�>��
strange
Every time the output is 'very' followed by the same amount of characters in the second array. This outputs correctly if I change the first line to
char text1[] = "very";
or if I don't declare and cout a second array.
Must have something to do with the way char is initialized with {'', '', '', ...}.. I notice that in this case the sizeof(text1) is 4 and in the case of using char text1[] = "very"; the sizeof(text1) is 5 with the last position being left blank. When declaring the second char the first char sizeof is still accurate however the second char is positions immediately after the first char in memory.
If I rewrite the program like this...
int main() {
char text1[] = {'v', 'e', 'r', 'y'};
char text2[] = "strange";
cout << text1 << endl;
cout << text2 << endl;
return 0;
}
The output becomes:
verystrange
strange
It seems that if I declare more char arrays it always slips the last one right in after the first one (text1[]) and it bumps the others forward in memory to make room. It only happens with using {}; to initialize. Really just wondering what's going on here... I can't see this causing any problems in a well written program.