可能是&或类似的东西丢失(我是cpp的noob。)
我有
string R = "somthing";
char* S;
如何将R
复制到S
答案 0 :(得分:32)
有很多方法。这里至少有五个:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
答案 1 :(得分:18)