I want to access starting address of the array that is maintained by the string class.
string str="hey";
char* pointer=(char*)str.c_str();
Is the pointer pointing to the address of the array(maintained by the string class)? or string class will create a new array from dynamic memory and copy the existing string into it and return it's address?
If this is not the right way, then how to access the starting address of the array that is maintained by the string class?
In C++11 standard it's explicitly stated that .c_str()
(as well as newer .data()
) shall return pointer to the internal buffer which is used by std::string
.
Any modification of the std::string after obtaining the pointer via .c_str()
may result in said char *
returned to became invalid (that is - if std::string
internally had to reallocate the space).
In previous C++ standards implementation is allowed to return anything. But as standard do not require user to deallocate the result, I've never seen any implementation returning anything newly allocated. At least GNU gcc's and MSVC++'s STL string are internally zero-terminated char arrays, which are returned by c_str()
.
So it's safe to assume (with normal for C++ caution) that in any version of C++ in any it's implementation .c_str()
will return internal buffer.
In other words - you should never ever keep the value of the .c_str()
unless you are 100% sure it's won't change it's size anytime in future (unless it's a const
, that is).
P.S. BTW, you should never ever do char* pointer=(char*)str.c_str();
. It's const char *
and you shall not modify the contents, partly because the above - you may end-up overwriting memory of some other object or corrupting internal state of std::string
, in case implementation doing something fancy, like indexing characters for faster .find()
(newer seen that, but hey - that's an encapsulation!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With