Is it correct that in order to get a char pointer to the end of a string
in C++ i have to do this:
std::string str = ...
const char * end_ptr = &*str.cend();
Like dereferencing, then getting the address of the expression. Is there a more elegant way to do this?
const char* end_ptr = str. c_str() + str. size(); to get a pointer to the terminating '\0' .
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed.
string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
I don't think that this is guaranteed, I'd use
const char* end_ptr = str.c_str() + str.size();
to get a pointer to the terminating '\0'
.
You solution is not correct. It will lead to undefined behavior. You cannot dereference str.cend()
:
Returns an iterator to the character following the last character of the string. This character acts as a placeholder, attempting to access it results in undefined behavior.
You can do
const char* end_ptr = &str[str.size() - 1];
As pointed out in comment, this will be one bit short.
You can use std::c_str
to match the exact behavior you want and get a pointer to the \0
:
Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.
The pointer is such that the range
[c_str(); c_str() + size()]
Then you just have to
const char* end_ptr = str.c_str() + str.size();
// or in c++11 you can use data()
Assuming you have at least one character in your string.
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