Home > Net >  abnormal behaviour in cout. It is printing twice character array after declaration of another same v
abnormal behaviour in cout. It is printing twice character array after declaration of another same v

Time:01-22

So I was writing the code to print a character array in c . The normal code is:-

#include <iostream>
using namespace std;

int main()
{
    char X[5] = {'A', 'B', 'C', 'D', 'E'};
    cout << X << endl;
    return 0;
}

and it's printing:-ABCDE as expected but I tried to create another character array like this

#include <iostream>
using namespace std;

int main()
{
    char X[5] = {'A', 'B', 'C', 'D', 'E'};
    char Y[5] = {'A', 'B', 'C', 'D', 'E'};
    cout << X << endl;
    return 0;
}

and I thought that I'll get same output but it didn't happend. the output was ABCDEABCDE I didn't understood why it happened.
At that time I was coding in my computer. So, I visited online c compiler and still got the same result.
Please anyone help me to understood why it happened? I am using C 14 in my computer. This is the link of online compiler website on which I rechecked my code.

CodePudding user response:

The behaviour is undefined.

std::ostream's overload for a const char* (selected due to pointer decay), doesn't stop outputting until NUL is reached.

So including NUL terminators in both arrays is the fix:

char X[/*let the compiler do the counting*/] = {'A', 'B', 'C', 'D', 'E', 0};

&c.

  •  Tags:  
  • Related