Remove constant from variable

I am trying to remove a constant from a variable (char *), but for some reason, when I try to change the value, the original value of the const constant remains unchanged.

const char* str1 = "david"; char* str2 = const_cast<char *> (str1); str2 = "tna"; 

now the value of str2 changes, but the original value of str1 remains unchanged, I searched it on Google, but could not find a clear answer.

when using const_cast and changing the value, should the source of the constant variable also change?

+7
source share
2 answers

Type str1 - const char* . This is char , not const , not a pointer. That is, it is a pointer to const char . This means that you cannot do this:

 str1[0] = 't'; 

This will change the value of one of const char s.

Now what do you do when you do str2 = "tna"; , the value of the pointer changes. It's great. You just change str2 to point to another string literal. Now str1 and str2 point to different lines.

Using the const const pointer, you can do str2[0] = 't'; - however, you will have undefined behavior. You cannot change something that was originally declared const . In particular, string literals are stored in read-only memory, and trying to change them will lead to a terrible misfortune.

If you want to take a string literal and change it safely, initialize the array with it:

 char str1[] = "david"; 

This will copy the characters from the string literal to the char array. Then you can change them to your liking.

+10
source

str2 is just a pointer. And your code just changes the value of the pointer, the address, and not the line it points to.

What else, what you are trying to do leads to undefined behavior and most likely leads to runtime errors. All modern compilers will store your "david" string in read-only memory. Attempts to change this memory will result in memory protection errors.

+3
source

All Articles