string c_str相关问题

青蛙球B 2017-03-24 01:17:12

#include <stdio.h>
#include <string>

std::string TestStr()
{
std::string ret = "test";
return ret;
}

void main()
{
std::string teststr = TestStr();
const char* test = TestStr().c_str();

printf("1: %s\n", test); //输出 空 或 乱码
printf("2: %s\n", TestStr().c_str()); //输出 "test"
printf("3: %s\n", teststr.c_str()); //输出 "test"
system("pause");
}


为什么2和3都能打出"test",但1却打不出来?
...全文
63 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
paschen 版主 2017-03-24
  • 打赏
  • 举报
回复
const char* test = TestStr().c_str(); 这句指向的是一个临时的对象(函数返回的string) 语句执行完这个临时的string就析构了 printf("2: %s\n", TestStr().c_str()); 这句是在printf后临时的string才销毁 printf("3: %s\n", teststr.c_str()); 这句中的string对象不是临时的
hellokubby 2017-03-24
  • 打赏
  • 举报
回复
test是指针,他代表一个地址

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧