如何从标准字符串 (c_str()) 中设置字符 * 值不起作用

how to set char * value from std string (c_str()) not working

本文关键字:设置 不起作用 字符 标准 字符串 str      更新时间:2023-10-16
我不知道

,但这对我不起作用,当我尝试从返回 std 字符串的函数中设置 char * 值时,我获得了 garbege 值:

string foo()
{
  string tmp ="dummy value";
  return tmp;
}
char* cc = (char *) foo().c_str(); // if i remove the casting im getting error 
// when i print the cc i get garbage 
printf("%s",cc);

cc指向的数据的生存期与它来自的字符串的生存期相同(充其量 - 如果你修改字符串,它甚至更短)。

在您的情况下,foo() 的返回值是一个临时值,在 cc 初始化结束时被销毁。

为了避免在char *cc = foo().c_str()中编译错误,你不应该投射到char*,你应该切换到const char *cc,因为const char*c_str()返回的内容。不过,这仍然不能解决主要问题。

最简单的修复是:

printf("%s", foo().c_str()); // if you don't need the value again later
const string s = foo();
const char *cc = s.c_str();  // if you really want the pointer - since it's
                             // in the same scope as s, and s is const,
                             // the data lives as long as cc's in scope.
string s = foo();
printf("%s", s.c_str());     // if you don't store the pointer,
                             // you don't have to worry about it.
std::cout << foo(); // printf isn't bringing much to this party anyway.
foo的结果

是一个临时对象,在char * cc = ...行末尾被销毁。将其存储在常量引用中:

const string& cc = foo();
printf ("%s", cc.c_str());

将内存位置传递给 foo() 并让 foo 修改它:

void foo (string* _out_newStr)
{
    _out_newStr->assign("dummy string"); //This is wrong -> _out_newStr = "dummy string";
    return;
}

然后,当您使用字符串对象的 "c_str()" 函数时,您将返回一个 const char* 值,如前所述。

代码片段调用未定义的行为,因为从调用创建的临时std::string在表达式结束时被销毁,但指向已销毁对象的cc即使在该之后仍会使用。

怎么样:

printf("%s", foo.c_str() );

或者更好的是,忘记使用字符指针。