簡體   English   中英

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

[英]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 = ... line的末尾破壞。 將其存儲在常量參考中:

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() );

或者更好的是,忘記使用字符指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM