将字符串转换为char*

18

1
为什么这个问题被踩了两次? - john
@john:也许有些人认为这个问题是重复的,或者他们认为这个问题没有展示出足够的努力,我真的不知道。对于一个初学者来说,这并不是一个显而易见的问题,但在这种情况下,我不指望看到那些踩票者的评论,因为它是一个重复的问题。 - Zeta
2
@Zeta 或许吧,但是在任何重复的迹象出现之前就有人投下了负评。对我来说,这似乎是不礼貌的行为。 - john
2个回答

45

有很多方法。以下至少有五种:

/*
 * 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);
}

8
c_str()函数创建的是const char *,而不是char *。 - Dani

19

首先,您需要分配内存:

char * S = new char[R.length() + 1];

然后您可以使用 strcpySR.c_str() 结合起来使用:

std::strcpy(S,R.c_str());

如果字符串不会被更改或C字符串只使用一次,您还可以使用R.c_str()。 但是,如果S将要被修改,则应该复制字符串,因为写入R.c_str()会导致未定义的行为。

注意:除了strcpy之外,您还可以使用str::copy


<string>.c_str()非常适合将字符串作为char*类型读取一次,以进行某种处理。 - gbmhunter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接