0

I'm new with C++ and I'v write this program:

#include <iostream>
#include <string>

using namespace std;

void main() {
    char s[2] = { 'a', 'l' };
    cout << s << endl;
}

And when I run this code I get wrong output like this:

al╠╠╠╠╠╠H²O

Why? because when I learn C++ I'v read when I print characters array I will see array elements like string.

AliOsm
  • 541
  • 2
  • 6
  • 20
  • `s` isn't zero-terminated. When passed to `cout` it decays into a `char*`, a C-style string. It needs to be zero-terminated, since there is no length information attached. – IInspectable Feb 13 '16 at 22:58
  • ╠ is 0xCC in codepage 437, and [MSVC fills 0xCC to uninitialized memory to help debugging](https://stackoverflow.com/q/370195/995714). That means you've accessed uninitialized memory. You can find tons of questions about ╠ and 0xCC here on SO – phuclv Aug 18 '18 at 10:56

1 Answers1

1

Your char array is not zero terminated, std::cout does not know where your string ends.

You need to do this:

char s[3] = { 'a', 'l', '\0'};
Emil
  • 384
  • 2
  • 11