Copy a string: Difference between revisions

Content added Content deleted
(added ocaml and scheme)
(→‎{{header|C++}}: Copying from std::string to C string and back)
Line 92: Line 92:
std::string src = "Hello";
std::string src = "Hello";
std::string dst = src;
std::string dst = src;

Standard C++ strings are not guaranteed to be stored contiguous, as needed for C functions, and it's only possible to get pointers to constant C strings. Therefore if the C function modifies the string, it has to be copied into a C string. There are several ways, depending on the needs:

Using a <tt>std::vector</tt> allows C++ to manage the memory of the copy. Since C++2003 (TR1), std::vector is guaranteed to be contiguous; but even before, there was no implementation which wasn't.

#include <string>
#include <vector>

std::string s = "Hello";
{
// copy into a vector
std::vector<char> string_data(s.begin(), s.end());
// append '\0' because C functions expect it
string_data.push_back('\0');
// call C function
modify(&string_data[0]);
// copy resulting C string back to s
s = (&string_data[0]);
} // string_data going out of scope -> the copy is automatically released

Another way is to manage your memory yourself and use C functions for the copy:

#include <string>
#include <cstring> // For C string functions (strcpy)

std::string s = "Hello";
// allocate memory for C string
char* cs = new char[s.length() + 1];
// copy string into modifyable C string (s.c_str() gives constant C string)
std::strcpy(cs, s.c_str());
// call C function
modify(cs);
// copy result back into s
s = cs;
// get rid of temporary buffer
delete[] cs;

If the C function calls free or realloc on its argument, new[] cannot be used, but instead malloc must be called:

#include <string>
#include <cstring>
#include <cstdlib> // for malloc

std::string s = "Hello";
// allocate memory for C string
char* cs = (char*)malloc(s.length()+1);
// copy the string
std::strcpy(cs, s.c_str());
// call C function which may call realloc
modify(&cs);
// copy result back to s
s = cs;
// get rid of temporary buffer
free(cs); // delete or delete[] may not be used here


'''Libraries:''' [[Qt]]
'''Libraries:''' [[Qt]]