Skip to content
Fix Code Error

How to convert a std::string to const char* or char*?

March 13, 2021 by Code Error
Posted By: Anonymous

How can I convert an std::string to a char* or a const char*?

Solution

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = ''; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost::scoped_array

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = ''; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('');

// get the char* using &writable[0] or &*writable.begin()
Answered By: litb

Related Articles

  • What are the new features in C++17?
  • How to properly do JSON API GET requests and assign…
  • Multiple separate IF conditions in SQL Server
  • no match for ‘operator
  • is there a way to use the forwarding of std::less…
  • Getting weird compilation error in defining a…
  • I do not use TBB, but I get linker errors related to TBB
  • TypeScript metadata reflection references other…
  • stringstream, string, and char* conversion confusion
  • Callback functions in C++
  • Proper use of the IDisposable interface
  • What is the copy-and-swap idiom?
  • C++ template,typename and operator
  • C++ : How can I parallelize an n-ary operation on n ranges?
  • C++ Need help sorting a 2D string array
  • Creating an dynamic array, but getting segmentation…
  • String.Format alternative in C++
  • What is use of c_str function In c++
  • Maximum XOR With an Element From Array | Leetcode
  • Oracle: If Table Exists
  • How do I print out the contents of a vector?
  • Smart way to truncate long strings
  • Unexpected behaviour java priority queue. Object…
  • std::string to char*
  • How to implement `au run --watch` task + debugging
  • How to write a large buffer into a binary file in C++, fast?
  • Copy a file in a sane, safe and efficient way
  • Function works perfectly but changes value after return
  • Why my pointer becomes dangling pointer in c++?
  • How do I use shell variables in an awk script?
  • Baffling variadic templates exercise
  • How do malloc() and free() work?
  • C free(): invalid pointer
  • How to convert wstring into string?
  • What is your most productive shortcut with Vim?
  • What is The Rule of Three?
  • Error with C++20 ranges and std::views::take
  • dart-polymer update polymer dom elements
  • How to filter a RecyclerView with a SearchView
  • What is a lambda expression in C++11?
  • apache server reached MaxClients setting, consider…
  • How to overwrite operator in C++ class with a…
  • Computing truncated mean between two forward indicators
  • Qt program with OpenGL + GLSL integration crashes…
  • Pods stuck in Terminating status
  • Right way to split an std::string into a vector
  • How do you convert CString and std::string…
  • How do I get currency exchange rates via an API such…
  • When should I use Write-Error vs. Throw? Terminating…
  • How to use Svelte store with tree-like nested object?
  • unique_ptr is not deleted after calling reset
  • How can I find the product GUID of an installed MSI setup?
  • Do you (really) write exception safe code?
  • "gatsby-source-airtable" threw an error while…
  • Laravel blank white screen
  • Use of Jquery on scroll event
  • Is there a way to treat React components as strings?
  • What's wrong with 'template int compare(char p1 [N],…
  • Octave using 'for' statement to show two animations…
  • Start redis-server with config file
  • How can I create an executable to run a kernel in a…
  • How does PHP 'foreach' actually work?
  • Head pointer not accessible when creating a method…
  • What does "dereferencing" a pointer mean?
  • Delete list element using element pointer
  • Is it possible to declare two variables of different…
  • How to find memory leak in a C++ code/project?
  • Confirm deletion in modal / dialog using Twitter Bootstrap?
  • Working with strings in C, strcat and the strange…
  • C threads corrupting each other
  • Is it possible to print a variable's type in standard C++?
  • Dynamically allocating an array of objects
  • How do I pass a unique_ptr argument to a constructor…
  • How to insert data in only one type of Vector in…
  • Overload operator delete to not delete object -…
  • What does "Fatal error: Unexpectedly found nil while…
  • How to allocate aligned memory only using the…
  • problem with client server unix domain stream…
  • Logging best practices
  • LNK2019 símbolo externo public: bool __thiscall ……
  • How to generate a random number in C++?
  • Apache server keeps crashing, "caught SIGTERM,…
  • How can I read and parse CSV files in C++?
  • Fastest way to iterate over all the chars in a String
  • Ukkonen's suffix tree algorithm in plain English
  • How to dispatch a Redux action with a timeout?
  • How do I sort a vector of pairs based on the second…
  • Create a directory if it doesn't exist
  • What is move semantics?
  • creating triggers for After Insert, After Update and…
  • Make free shipping available for certain shipping…
  • Using Auto Layout in UITableView for dynamic cell…
  • Text size and different android screen sizes
  • How to convert number to words in java
  • Ways to save Backbone.js model data?
  • Merging 3 files together, works fine when merging…
  • What is the worst programming language you ever worked with?
  • How do I delete a Git branch locally and remotely?
  • VueJS How to pass data to a modal component using eventbus
  • What is the difference between new/delete and malloc/free?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Difference between == and === in JavaScript

Next Post:

Java URL encoding of query string parameters

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error