The array return by this function is a const pointer to the internal representation of the string str. But since the pointer is constant we don't risk to modify accidentally the value of str:
1 2 3 4 5 6 7 8 9
constchar* chrPtr = newchar[str.length() + 1];
chrPtr = str.c_str();
//ok, now we have another pointer which is pointing to the same memory location
//of the internal pointer that represents the str string
chrPtr[2] = 'a';//ERROR: chrPtr is constant.
//ok, if we want to have our copy we use strcpy()!
char* chrPtr1 = newchar[str.length() + 1];
strcpy(chrPtr1, chrPtr);
chrPtr1[2] = 'a';//ok, you can do it!
Yes, you are correct.
However in your code you have a memory leak:
on line 1 you allocate an array.
on line 2 you lose pointer to it, making it impossible to delete.
pointer returned by c_str() becomes invalid if any non-const member of string it belongs to is called.
To make you code more safe, you do not even need the first pointer. just:
c_str() does not returns pointer to internal representation. It returns pointer to c-string which has same content as original string.
Here it's said that the the array return by c_str() is the internal representation (if I didn't misunderstand): http://www.cplusplus.com/reference/string/string/c_str/
That gives a memory leak, a buffer is allocated and its address is immediately replaced with some other value thus the buffer is no longer accessible
Ok, you are right, I give another address to a pointer that I have just allocated in somewhere else, right.
Ok, basically we don't need the const char*, also because strcpy() accepts just a char* as first argument and not a const one.
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
It is representing same value, not pointing to representation. Basically str[x] == str.c_str()[x].
EDIT: in C++11 requirement &str[x] == &str.c_str()[x] was added. So you can say that it points to internal storage. However trying to change something through it leads to undefined behavior, as string can store some other related information separate from that array.
EDIT: in C++11 requirement &str[x] == &str.c_str()[x] was added. So you can say that it points to internal storage. However trying to change something through it leads to undefined behavior, as string can store some other related information separate from that array.
Yes, I was exactly talking about this part. Yes, but we can't modify str.c_str() anyway, because its a reference to constant data! (const char*)
Usind unsafe casts everything is possible: ((char*)str.c_str())[1] = 'o';. However this leads to undefined behavior and your computer has a chance of exploding.