c-string explanation

Write your question here.

[#include<iostream>
using namespace std;

int main() {
char name[] = {'A', 'm', 'y', '\0'}; // a C-string
char name2[] = {'A', 'm', 'y'}; // not a C-string

cout << name; // normal output
cout << endl;
cout << name2; // strange output
cout << endl;

return 0;
}]
why both name & name2 output is same? I was expecting name2 different output, because of the absence of null vector.
[/code]
The behavior of cout << name2; is undefined. The output may be the same, it may be different, or the program might even eat your hard drive.
Last edited on
The name2 is an array of three bytes somewhere in (stack) memory. There is (most likely) more memory after that array. What values are in those bytes that are after your array? Impossible to know. Undefined.

In your test run there apparently were only values that did not visibly change the output. Consider yourself unlucky. It is better to crash and burn than to believe that everything is ok.
Topic archived. No new replies allowed.