如何设置char *值从std字符串(c_str())不工作 [英] how to set char * value from std string (c_str()) not working

查看:102
本文介绍了如何设置char *值从std字符串(c_str())不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道,但这不是我的工作我获取garbege值,当我尝试设置char *值从返回std字符串的函数:

i dont know but this not working for me im getting garbege value when i try to set char * value from function that returns std string :

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指向的数据的生命周期$ c> cc 与字符串的生命周期相同(最多 - 如果修改字符串,它甚至更短)。

The lifetime of the data pointed to by cc is the same as the lifetime of the string it came from (at best - if you modify the string it's even shorter).

在你的情况下, foo()的返回值是在 cc

In your case, the return value of foo() is a temporary that is destroyed at the end of the initialization of cc.

为避免 char * cc = foo()。c_str()不应转换为 char * ,应切换到 const char * cc ,因为 const char * 是什么 c_str()返回。但

To avoid the compilation error in char *cc = foo().c_str() you shouldn't cast to char*, you should switch to const char *cc, since const char* is what c_str() returns. That still doesn't solve the main problem, though.

最简单的修复是:

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.

这篇关于如何设置char *值从std字符串(c_str())不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆