'\0' in character array

char a[] = {‘a’, ‘b’, ‘c’};
string s5(a);
cout << s5;

When i did not put ‘\0’ character at the end of character array ,put a into the string and then printed the string, the output was - abc��a .
What did actually happen which led to the above result?
(if there was not a ‘\0’ then the string should have continued as it does not know the end or if it does then the output should have been - abc)

hi @akashagarwal1321

char a[] = {'a', 'b', 'c'};
string s5(a);
cout << s5;

if u dont put ‘\0’ at the end then it takes garbage value and print result as ‘\0’ is used as a terminator in character array…

char a[] = {'a', 'b', 'c','\0'};
string s5(a);
cout << s5;

if u put ‘\0’ at the end then o/p comes correct ie abc

i hope its clear now??

but if it takes garbage value then how ‘a’ is printed again in abc��a?
^

That’s a random value… run it again and it will give different o/p

1 Like

yes , i got it :slight_smile:
Thank you so much.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like