When I "cout" an empty array, I get gibberish. Why?
int main() { char test[10]; cout << test; return 0; }
...returns some unicode blather. An easy answer I'm sure.
When I "cout" an empty array, I get gibberish. Why?
int main() { char test[10]; cout << test; return 0; }
...returns some unicode blather. An easy answer I'm sure.
Because your array isn't initialized. Its contents can be anything, and you get undefined behavior using them.
You can initialize them all to zero:
char test[10] = {};
And when printed, will print nothing.
Your array isn't initialized to anything and you're outputting the first element of that uninitialized array.
If you want predictable behavior, you need to initialize the array first (the following initializes to an empty array):
int main() { char test[10] = {}; cout << test; return 0; }
Since you didn't initialize the array you got a garbage value (test[0] is what you are printing out).
Initialize it:
int main() {
char test[10] = {};
cout << test;
return 0;
}
Just like to note:
Just because some compilers initialize stuff (like some compilers initialize ints, floats etc., at 0) it is not always the case, and you can get a garbage value otherwise.
There's no such thing as an "empty array" in C++. You defined an array of 10 chars - you got an array of 10 chars. Since it is a local array, by default it is left uninitialized, meaning that each of the 10 chars contains garbage. That garbage is what you printed.