.c_str()
In C, the .c_str()
method returns a pointer to a null-terminated array of characters, equivalent to the contents of the string on which it is called.
The c_str()
method is commonly used when a C-style string is needed, such as when passing a std::string
to functions that expect a const char*
. It’s especially useful for interoperability with legacy C libraries or APIs like printf()
, fopen()
, or other system-level functions.
Note: The
.c_str()
method runs in constant time O(1), as it returns a pointer to the internal character array of the std::string.
Syntax
string.c_str()
Parameters:
The .c_str()
method does not take any parameters.
Return value:
Returns a const char*
, which is a pointer to a null-terminated character array representing the contents of the string.
Example
This example shows the size of a std::string
object and a pointer returned by .c_str()
, along with the actual string length using length()
and strlen()
:
#include <string>#include <iostream>#include <cstring> // for strlenint main() {std::string str = "Foobar";const char* arr = str.c_str();std::cout << "Size of 'arr' (pointer): " << sizeof(arr) << " bytes" << std::endl;std::cout << "Size of 'str' (std::string object): " << sizeof(str) << " bytes" << std::endl;std::cout << "Length of string using str.length(): " << str.length() << std::endl;std::cout << "Length of string using strlen(arr): " << strlen(arr) << std::endl;return 0;}
The output of this code is:
Size of 'arr' (pointer): 8 bytesSize of 'str' (std::string object): 32 bytesLength of string using str.length(): 6Length of string using strlen(arr): 6
Note:
sizeof
gives the size of the variable’s type, not the number of characters.
Codebyte Example
In this codebyte example, we have a function printPointerCharArrToStdOut
that expects a pointer to a character array. The .c_str()
method is used to convert a std::string
to a C-style string, allowing it to be passed to the function. The function then outputs each character of the array individually:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours