C++ std::string with char*

C++ std::string is a dynamic, contiguous container for character strings. String data is easily and efficiently passed between std::string to / from a C or Fortran function that expects a char* pointer.

The basic algorithm is:

  1. allocate std::string with desired size and fill with \0.
  2. use std::string::data() to get a char* pointer to the string data that is read/write for the C or Fortran function (or C++).
  3. use std::string::c_str() to get a const char* pointer to the string data that is read-only for the C or Fortran function (or C++). This trims the string to the first \0 character. Otherwise, the std::string::length() will include all the unwanted trailing \0 characters.

example