Question

i'm trying to remove const-ness from a variable (char*), but for some reason when i try to change the value, the original value of the const variable still remains the same.

 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 the same, i've looked it up on Google but couldn't find a clear answer.

when using const_cast and changing the value, should the original of the const variable change as well ?

Was it helpful?

Solution

The type of str1 is const char*. It is the char that is const, not the pointer. That is, it's a pointer to const char. That means you can't do this:

str1[0] = 't';

That would change the value of one of the const chars.

Now, what you're doing when you do str2 = "tna"; is changing the value of the pointer. That's fine. You're just changing str2 to point at a different string literal. Now str1 and str2 are pointing to different strings.

With your non-const pointer str2, you could do str2[0] = 't'; - however, you'd have undefined behaviour. You can't modify something that was originally declared const. In particular, string literals are stored in read only memory and attempting to modify them will bring you terrible misfortune.

If you want to take a string literal and modify it safely, initialise an array with it:

char str1[] = "david";

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

OTHER TIPS

str2 is simply a pointer. And your code just changes the value of the pointer, the address, not the string to which it points.

What's more, what you are attempting to do leads to undefined behaviour, and will most likely result in runtime errors. All modern compilers will store your string "david" in read-only memory. Attempts to modify that memory will lead to memory protection errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top