"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Do I Convert a C++ std::string to a char* or char[]?

How Do I Convert a C++ std::string to a char* or char[]?

Posted on 2025-03-23
Browse:541

How Do I Convert a C   std::string to a char* or char[]?

Converting std::string to char* or char[]

Converting a std::string to char* or char[] data types in C requires explicit methods, as they do not automatically convert.

Method 1: Using c_str()

To obtain a C-string version of the std::string, use the c_str() method. This method returns a const char. For a non-const char, use .data():

std::string str = "string";
const char *cstr = str.c_str(); // const char*
char *cstr = str.data(); // non-const char*

Method 2: Copying into a Vector

Copy the std::string characters into a std::vector:

std::vector cstr(str.c_str(), str.c_str()   str.size()   1);
char *ptr = cstr.data(); // pointer to c-string

Method 3: Manual Array Allocation (Not Recommended)

Manually allocate an array for the C-string:

const char *cstr = new char[str.size()   1];
std::strcpy(cstr, str.c_str());
// ... use the array ...
delete [] cstr;

It's crucial to remember that manual memory management can lead to errors. As a best practice, prefer using .c_str() or .data().

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3