Conversion from std::string to char *, is there a better way?

From: Julie (julie_at_nospam.com)
Date: 06/10/04


Date: Thu, 10 Jun 2004 10:48:33 -0700

I'm re-evaluating the way that I convert from a std::string to char *.
(Requirement: the source is a std::string, the usable contents are char *)

Here is what I've come up with:

#include <string>
#include <vector>
#include <cstring>

  // presume s from somewhere, such as:
  std::string s = "<initial value>";

  std::vector<char> v(s.length() + 1);
  std::strcpy(&v[0], s.c_str());
  char * c = &v[0];
  // use c, where a char * is _specifically_ required
  s = c;

The above:
 - doesn't use any pointers that must be manually deallocated
 - is 100% portable(?)
 - is 100% conformant(?)

I've seen Bjarne's similar implementation, but it uses new char * instead of
vector (obviously written before the STL was adopted).

auto_ptr<char> in place of vector<char> doesn't work because it doesn't handle
arrays.

Does anyone have comments on the above, specifically as to its suitability for
the requirements defined?



Relevant Pages

  • Re: char vs int
    ... 'a' is a character constant. ... A variable of type char can ... of them instead of int arrays. ... concept of pointers. ...
    (comp.lang.c)
  • Re: Invalid conversion from char tp char*
    ... Consider using std::strings instead of char arrays. ... search as much for the declaration of an object. ... The problem is that array sizes must be compile-time constants. ... You should also prefer standard containers to arrays. ...
    (comp.lang.cpp)
  • Re: trying to construct an array.....corrected
    ... May I ask why this char is volatile? ... (which points to the string literal in question). ... Arrays are meant for a collection of data of the same type. ... What you're looking for is a struct. ...
    (comp.lang.c)
  • Re: sscanf problem.
    ... I use TCHAR arrays very rarely; most commonly for APIs that want MAX_PATH sized buffers, ... and those tend to fall into the "rare and exotic" for me. ... CString and go on with life. ... char cs; ...
    (microsoft.public.vc.mfc)
  • Re: simple question regarding 5.5 of Ritchie & Kernighan
    ... pointers to char and arrays of char: ... a memory address to hold the value it points to and that memory address ... runtime) multidimensional arrays. ... arrays of pointers to arrays, ...
    (comp.lang.c)