Assigning to a const char* a char*

What exactly happens when I assign a char* to a const char*?

For example, suppose I have first allocated a char pointer with the following snippet of code:

char* chrPtr = new char[10];
Then I copy some characters in this char pointer and, at the end, I want to initialise a const char* with this char* pointer characters:

const char* stringLiteral = chrPtr;

Would the previous statement be valid, without any memory leak?
Last edited on
It's valid code. It just means the compiler will complain if you try to modify the characters using the stringLiteral pointer.
1
2
chrPtr[0] = 'A'; // OK
stringLiteral[1] = 'B'; // ERROR 
Ok, thanks. I asked this because I had written my own String class a few months ago, and I was reviewing it. Even if it passed just a few months without using C++, I had some doubts regarding this situation. In this case, the only thing that is constant is the content pointed by stringLiteral, right?
Last edited on
A pointer is a variable that holds a memory address as its value.

You assign the address of a dynamically allocated memory block to chrPtr. Just like you would do int x = 42;

Then you copy-assign the same value to an another pointer variable stringLiteral, just like you would do const int y = x;

You have allocated memory dynamically. You should deallocate that memory appropriately. Your code fragment does not say anything about it, but at least you still have the address stored (in two variables).


Just in case, lets use another analogy. You give your number to a girl. She gives it to her friend. Now they both (two pointers) can call (dereference) you. That in itself won't cast you to a dark hole, will it?
Topic archived. No new replies allowed.