How to Convert a std::string to char* in C++?
Last Updated :
14 Feb, 2024
Improve
In C++, strings are the textual data that is represented in two ways: std::string which is an object, and char* is a pointer to a character. In this article, we will learn how to convert a std::string to char* in C++.
Example
Input:
string myString = "GeeksforGeeks";
Output:
char * myString = "GeeksforGeeks";
Convert std::string to char* in C++
The std::string is also implemented using char array so it is very easy and straightforward to perform this conversion. To convert a std::string to a char*, we can use the std::string:c_str() method that returns a pointer to a null-terminated character array (a C-style string).
C++ Program to Convert std::string to char*
// C++ program to convert string to char*
#include <iostream>
#include <string>
using namespace std;
int main()
{
// declaring string
string myString = "Geeks For Geeks";
cout << "string: " << myString << endl;
// Using c_str() to get a pointer to a null-terminated
// character array
const char* charPointer = myString.c_str();
// Now you can use charPointer as a regular C-style
// string
cout << "C-style string: " << charPointer << endl;
return 0;
}
// C++ program to convert string to char*
using namespace std;
int main()
{
// declaring string
string myString = "Geeks For Geeks";
cout << "string: " << myString << endl;
// Using c_str() to get a pointer to a null-terminated
// character array
const char* charPointer = myString.c_str();
// Now you can use charPointer as a regular C-style
// string
cout << "C-style string: " << charPointer << endl;
return 0;
}
Output
string: Geeks For Geeks C-style string: Geeks For Geeks
Time Complexity: O(1)
Space Complexity: O(1)