如何从标准字符串 (c_str()) 中设置字符 * 值不起作用
how to set char * value from std string (c_str()) not working
我不知道
,但这对我不起作用,当我尝试从返回 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() );
或者更好的是,忘记使用字符指针。
相关文章:
- C++ Visual Studio Code 的设置不起作用
- Clang Tidy 插件 for Visual Studio Code 不起作用/如何设置
- 在qt QFileDialog中设置后缀在linux中不起作用,如何解决?
- 将复制构造函数设置为默认值在继承自 QObject 时不起作用
- glTexImage2D 不起作用,但将 FragColor 设置为 vec4(1.0, 0, 0, 1.0) 会给我红色图像
- 将字符数组设置为彼此相等的方法不起作用
- 设置c 代码示例,带有sqlite3不起作用
- setSockopt在C 中不起作用(超时设置为1s,等待更长的时间)
- 我无法正确获取这些变量声明...为什么这些参数不起作用?我只是将 n 值设置为数组长度
- 101 Qt 样式表边距填充黑客指南在C++。设置填充不起作用
- Mac OS X 中的设置区域设置不起作用
- 设置交叉点不起作用
- std::在C++中设置删除程序不起作用
- 在 c++ 中,如何远程设置注册表项(连接工作正常,但设置不起作用!
- 在 c++ 中设置函数不起作用
- 如何在OpenCV中设置相机的视频格式?CAP_PROP_FOURCC不起作用
- 设置固定 FPS 不起作用
- 设置图标不起作用
- 设置缩进宽度在咔嚓格式中不起作用
- C++是唯一的,并且设置不起作用