In the past i've been using Visual Studio 2010/2013/2015 and this syntax was possible :
char* szString = "This works!";
I've decided to step on and change my lifestyle of coding towards Linux, as I have installed g++ and have SlickEdit as my IDE.
It seems like that sentence doesn't work anymore. Can anyone please state why?
This works however :
char strString[] = "This works!";
The error is something with c++11.
Does anyone have an idea why this happens? Not how to fix it, cause in my workspace there isn't any way to install a c++11 compiler, i'm just curious if it has to do with something on the background on how the compiler works. What I do know about the first line of code, is that it creates a constant variable on the stack and creates a new pointer setting itself towards that ESP's value, but on the second one it counts the amount of letters on the constant variable and then sets a null terminator in the end as a result.
Oh and one more thing -> There seems to be a difference also in the way the first one is set in GCC/GPP, as the first type is {char*&} and the second one is {char(*)[12]}, any explanation on that too? Thanks!
When you write the literal "text"
, that text will be included somewhere the compiled program image. The program image is usually placed in write-protected memory on modern operating systems for security reasons.
char* someString = "text";
declares a pointer to the string in your probably-write-protected program image. The ability to declare this pointer as non-const was a feature included until C++11 to maintain source compatibility with C. Note that even though someString
is not a pointer-to-const, any attempt to modify the value that it points to will still result in undefined behavior. This backwards compatibility feature was removed in C++11. someString
must now be declared as pointer-to-const: const char* someString = "text";
. You can cast the const
away, but attempting to write to the value pointed to will still result in undefined behavior the same as any const
value you cast to non-const.
char someString[] = "text";
works differently. This copies the string "text"
from your program's code memory into an array located in data memory. It's similar to
char someString[5];
strcpy(someString, "text");
Since someString
is an array in your program's data memory, it's fine to write to it, and it doesn't need to be const-qualified.