Originally Posted by
Ancient Dragon
you can't delete it becase you tossed out the allocated memory when you reassigned the pointer to the constant string literal. The pointer now points to the memory location occupied by "dkdk" instead of the memory allocated by the new operator.
use strcpy() to copy the string. the assignment operator = only works with std::string objects.
Why do you say that? You can assign both the address of a char array to a char pointer and the address of a string literal to a char pointer:
Code:
#include<iostream>
using namespace std;
int main()
{
char* k;
k = new char[30];
delete [] k;
k = "dkdk";
cout<<k<<endl;
return 0;
}
cunnus88,
The compiler takes a string literal(i.e. anything enclosed in double quotes) and slaps a '\0' character onto the end and stores it in memory somewhere and returns it's address, which is assigned to your pointer variable. The compiler also makes the string literal in memory a const, so you can't change it. You may wonder how the const value in memory can be assigned to your non-constant pointer: char* k. Normally, a non-const pointer allows you to change the value the pointer points to. But, that isn't the case with string literals, and if you try to use k to change the value of the string literal in memory, your program will crash at runtime. Here is an example:
Code:
char* k = "some text";
k[0] = 'a';
Compiles fine, crashes when you run it. The reason the compiler won't flag that as an error is for backwards compatibility for code that was written before the C++ standard made string literals constant. Therefore, it's good practice and may prevent nasty runtime errors if you declare your pointer variable const when you are going to assign it a string literal:
Code:
const char* k = "some text";
That way if the code you write tries to change the string literal, the compiler will flag it as an error instead of letting it go, causing your program to experience a mysterious runtime crash.
Code:
const char* k = "some text";
k[0] = 'a'; //error
When the compiler notifies you of an error, you can correct it. Note how this is one way to write C++ code that uses the compiler to help you catch errors. If the errors are caught by the compiler, then you can fix them. Otherwise, you might not discover them, and when you or a client is running your program it will mysteriously crash.