如何设置std字符串(c_str())中的char*值不起作用

use*_*898 5 c++ string pointers

我不知道但是当我尝试从返回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);
Run Code Online (Sandbox Code Playgroud)

Ste*_*sop 13

指向的数据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.
Run Code Online (Sandbox Code Playgroud)


Xio*_*ion 9

结果foo是一个临时对象被char * cc = ...行尾破坏.将其存储在常量参考中:

const string& cc = foo();
printf ("%s", cc.c_str());
Run Code Online (Sandbox Code Playgroud)