tags:

views:

136

answers:

5

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.

+8  A: 

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.

GMan
+1  A: 

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; }
Justin Niessner
+4  A: 

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.

thyrgle
Cheers mate, makes sense.
Steve
+4  A: 

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.

AndreyT
A: 
Montdidier
dreamlax
"Also remember array and pointer equivalence(s)" There are no equivalences, they are different types.
GMan
good points and I was not clear - I meant equivalence describing certain properties, not talking about type equivalence. As taught in many C and C++ classes around the world. e.g. eskimo.com/~scs/cclass/notes/sx10e.html. Probably inappropriately named, but widely understood none the less.
Montdidier
or rather http://eskimo.com/~scs/cclass/notes/sx10e.html
Montdidier