What exactly happens when I assign a char* to a constchar*?
For example, suppose I have first allocated a char pointer with the following snippet of code:
char* chrPtr = newchar[10];
Then I copy some characters in this char pointer and, at the end, I want to initialise a constchar* with this char* pointer characters:
constchar* stringLiteral = chrPtr;
Would the previous statement be valid, without any memory leak?
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?
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 constint 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?