Know that
"abc"
allocates static storage somewhere, which lasts the whole program lifetime. You cannot write to that storage, so C++ gives it the type char const[N]
(an array of N constant characters). Now, the following makes a pointer point to that storage
char *first = "hi";
Since that drops a const
, that way of initializing the pointer is deprecated. That it works at all is just to keep backward compatibility with C, where a string literal does not have a const type (but is still read only). Prefer the following instead
char const *first = "hi";
In constrast, the last way you have shown copies the string literal's content to an array, which will be writable, and be sized so the string literal just fits into it.
char third[] = "new";
If you do that in a function, then as all variables, that array will be cleaned up when you leave its scope. Now, the first way you have shown is different. It creates a character dynamically. You could have initialized it like this
char *c = new char('A');
And since that happens dynamically, you need to tell the compiler explicitly when it should free the memory
delete c;
But you cannot initialize the character with a string literal. What you probably had in mind is creating storage dynamically, initialized with the string literal. That's not possible using new
. The only form of initializing a dynamic array is to zero it out, but you cannot directly-initialize with the content of a string literal or another array. For this form of using new
, there is rarely a need to do that directly. If you want, you can do it by creating a dynamic array of the right size, and then copy bytes from the string literal to that buffer
char *c = new char[sizeof "hello"]; // sizeof "hello" will give 6
std::strcpy(c, "hello");
delete[] c; // delete[] is for deleting dynamic arrays
Remember that this is quite low-level, and i recommend you to use strings
std::string s = "hello"; // s.size() gives you its size
It completely manages memory for you. Concatenation, indexing and that stuff is available too.