Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get end of string as const char * in C++

Tags:

c++

string

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?

like image 832
GOTO 0 Avatar asked Sep 15 '13 20:09

GOTO 0


People also ask

How do you get a pointer to the end of a string?

const char* end_ptr = str. c_str() + str. size(); to get a pointer to the terminating '\0' .

Can a char * be passed as const * argument?

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 ...

Can const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed.

What is the difference between const char * and string?

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.


2 Answers

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'.

like image 149
Daniel Frey Avatar answered Sep 29 '22 20:09

Daniel Frey


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.

like image 34
Pierre Fourgeaud Avatar answered Sep 29 '22 18:09

Pierre Fourgeaud