The C++11 Standard (ISO/IEC 14882:2011) says in § C.1.1
:
char* p = "abc"; // valid in C, invalid in C++
For the C++ it's OK as a pointer to a String Literal is harmful since any attempt to modify it leads to a crash. But why is it valid in C?
The C++11 says also:
char* p = (char*)"abc"; // OK: cast added
Which means that if a cast is added to the first statement it becomes valid.
Why does the casting makes the second statement valid in C++ and how is it different from the first one? Isn't it still harmful? If it's the case, why did the standard said that it's OK?
You can also use strdup:
char* p = strdup("abc");
It's valid in C for historical reasons. C traditionally specified that the type of a string literal was char *
rather than const char *
, although it qualified it by saying that you're not actually allowed to modify it.
When you use a cast, you're essentially telling the compiler that you know better than the default type matching rules, and it makes the assignment OK.
You can declare like one of the below options:
char data[] = "Testing String";
or
const char* data = "Testing String";
or
char* data = (char*) "Testing String";
Source: Stackoverflow.com