如何使用指针取回字符串数据?

How to get string data back using pointer?

我无法使用指向 char 数组的指针取回我的字符串数据。你能给我解释一下我做错了什么吗?

#include "stdafx.h"
#include <conio.h>
#include <string>

using namespace std;

string GetString()
{
    return string("255");
}

int _tmain(int argc, _TCHAR* argv[])
{
    char* str_p = const_cast<char*>(GetString().c_str());
    printf("Pointer : %s\n", str_p);
    string str;
    str = str_p[0];
    str += str_p[1];
    str += str_p[2];
    printf("Constructed : %s\n", str.c_str());

    _getch();
    return 0;
}

控制台输出为:

Pointer :
Constructed :

这一行有很多错误:

char* str_p = const_cast<char*>(GetString().c_str());

GetString()returns临时string。它在行尾被销毁。所以你最终得到一个指向已经被释放的内部数据的悬空指针。此外,const_cast 是只有当您 真的 需要它时才应该使用的东西 - 直接编辑数据只是自找麻烦。

如果您想要指向该字符串的指针,正确的做法是:

string old = GetString();        // make sure it doesn't go out of scope
const char* str_p = old.c_str(); // while this pointer is around