Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ cout fresh array gibberish

Tags:

c++

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.

like image 454
Ben Avatar asked Dec 09 '25 22:12

Ben


2 Answers

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.

like image 142
GManNickG Avatar answered Dec 12 '25 11:12

GManNickG


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!