Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

const char* allows to modify the string?

I understand that using const char* is a modifiable pointer to a constant character. As such, I can only modify the pointer, but not the character. Because of this, I do not understand why I am allowed to do this:

const char* str{"Hello World"};

str = "I change the pointer and in turns it changes the string, but not really.";

How does this work? Is there somewhere in memory where all the characters are stored and I can just point to them as I wish? Furthermore, the adress of str does not change throughout this process. Since the only thing that can change is the address, I really don’t understand what’s going on.

Maybe part of the problem is that I try to understand this as if the string was an integer. If I do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int number{3};
const int* p_number{&number};

*p_number = 4;

This is not valid, hence why I expect str to not by modifiable. In order words, where am I pointing so that "Hello World" becomes "I change the pointer and this changes the string"?

EDIT:

I get that I create a new string at another address, but when I do:

const char *str{"HelloWorld"};
std::cout << &str << std::endl;
str = "I create new string, but I get same address";
std::cout << &str << std::endl;

I always get the same address twice.

>Solution :

No string was replaced, you just reassigned str a new string which is stored on stack-memory.

Try this snippet, that the address was changed

#include <stdio.h>

int main(void)
{
    const char *ptr = "Hello";
    printf("Before: %p\n", ptr);

    ptr = "World";
    printf("After: %p\n", ptr);
}

Output [RESULT MAY VARY]:

Before: 0x402004
After: 0x402016
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading