char* stringReturn()
{
char a[] = "Array of characters";
//return a; // I know stack allocation should not be returned
char *b = "Pointer to a string";
return b; // Is it safe ?
}
int main() {
char *str = stringReturn();
cout<< str;
return 0; }
這是安全的意思,那麼數據「指向字符串的指針」將存儲在內存中。將指向字符串的指針返回給調用者是否安全?
可能的重複[http://stackoverflow.com/questions/2327841/c-string-literal-data-type-storage](http://stackoverflow.com/questions/2327841/c-string-literal-數據類型存儲) – jrok 2012-04-02 17:39:06
另請參閱:http://stackoverflow.com/questions/349025/is-a-string-literal-in-c-created-in-static-memory – 2012-04-02 17:39:28
請注意,實際上,您正在編寫C代碼,不用介意'std :: cout'。這有缺點。其中之一是字符串處理相當複雜和危險。 (對於初學者'b'應該是一個'const char *';嘗試修改它的調用者將炸燬地球,返回'a'也是一個災難,並且返回一個動態分配的字符數組成爲維護噩夢。你有沒有考慮過使用'std :: string'?這樣做,這些問題就會消失。 – sbi 2012-04-02 17:46:01