Copy a string: Difference between revisions

m
→‎{{header|C++}}: lang tag; lib -> libheader
m (→‎{{header|C}}: lang tag)
m (→‎{{header|C++}}: lang tag; lib -> libheader)
Line 101:
 
{{libheader|STL}}
<lang cpp> #include <string>
std::string src = "Hello";
std::string dst = src;</lang>
 
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:
Line 109:
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.
 
<lang cpp> #include <string>
#include <vector>
 
Line 122:
// copy resulting C string back to s
s = (&string_data[0]);
} // string_data going out of scope -> the copy is automatically released</lang>
 
Another way is to manage your memory yourself and use C functions for the copy:
 
<lang cpp> #include <string>
#include <cstring> // For C string functions (strcpy)
 
Line 139:
s = cs;
// get rid of temporary buffer
delete[] cs;</lang>
 
If the C function calls free or realloc on its argument, new[] cannot be used, but instead malloc must be called:
 
<lang cpp> #include <string>
#include <cstring>
#include <cstdlib> // for malloc
Line 157:
s = cs;
// get rid of temporary buffer
free(cs); // delete or delete[] may not be used here</lang>
 
=== Using string types supplied by specific compiler-provided or external libraries ===
 
{{libheader|Qt}}
'''Libraries:''' [[Qt]]
<lang cpp> // Qt
QString src = "Hello";
QString dst = src;</lang>
 
'''Libraries:''' [[{{libheader|Microsoft Foundation Classes]]}}
<lang cpp> // MFC
CString src = "Hello";
CString dst = src;</lang>
 
=={{header|C sharp|C #}}==