Why Does This Work

Why does this work?

1
2
3
4
5
6
char* pn=NULL;
char cchar[]="Tip toe through the tulips";

pn=cchar;

cout << pn << endl;


I played with super long strings and it still works.

I know that pn points to the address of cchar[0], but how does it know to allocate the right memory? And why don't I have to allocate memory in this case, whereas in other cases, I must allocate it?

Is it simply that I must do the allocating when I don't know the address of a string, such as reading data from a file, but when I do know the address of a string, the compiler automatically handles it?
The compiler knows how much memory to allocate because it can count the letters in the literal string you give it.
So in other words, a literal string doesn't need me to allocate memory for it, but a non-literal string does? It's that simple?
That's right. When your sample is compiled the compiler says "cchar needs to be a stack array with a copy of the string 'Tip toe through the tulips', so that measures 26, meaning I will make cchar an array of 27 chars and then copy the string literal, leaving cchar exactly the way the developer wants it: Allocated and containing the string".
Much obliged!
Topic archived. No new replies allowed.