Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make std::string compatible with char*?

Tags:

c++

I usually find some functions with char* as its parameter.But I heard that std::string is more recommended in C++. How can I use a std::string object with functions taking char*s as parameters? Till now I have known the c_str(), but it doesn't work when the content of string should be modified.

like image 383
noob_in_math Avatar asked May 05 '20 14:05

noob_in_math


3 Answers

For that purpose, you use std::string::data(). Returns a pointer to the internal data. Be careful not to free this memory or anything like that as this memory is managed by the string object.

like image 181
Ayxan Haqverdili Avatar answered Nov 15 '22 06:11

Ayxan Haqverdili


You can use the address of the first element after C++11 like this:

void some_c_function(char* s, int n);

// ...

std::string s = "some text";

some_c_function(&s[0], s.size());

Before C++11 there was no guarantee that the internal string was stored in a contiguous buffer or that it would be null terminated. In those cases making a copy of the string was the only safe option.

After C++17 (the current standard) you can use this:

some_c_function(s.data(), s.size());

In C++17 a non-const return value of std::string::data() was added in addition to the const version.

like image 23
Galik Avatar answered Nov 15 '22 06:11

Galik


Since C++17 std::string::data() returns a pointer to the underlying char array that does allow to modify the contents of the string. However, as usual with strings, you may not write beyond its end. From cppreference:

Modifying the past-the-end null terminator stored at data()+size() to any value other than CharT() has undefined behavior.

like image 25
463035818_is_not_a_number Avatar answered Nov 15 '22 05:11

463035818_is_not_a_number