推 littleshan:寫 char *c="hello" 一樣很危險 12/09 18:57
請問風險在於哪裡呢?
書中解法是傳回 const char*
const char* a()
{
char *cp="hello";
return cp;
}
※ 編輯: descent 來自: 115.43.245.118 (12/09 20:16)
推 littleshan:寫 char* 表示這塊資料可以被寫入,但寫了就炸了 12/09 20:35
→ littleshan:回傳 const char* 是對的 12/09 20:35
推 leav:每種C compiler實作的方式不太一樣 12/09 20:38
→ leav:static char[]會比較保險, 唯讀的就用static const char[] 12/09 20:40
→ atst2:重點是static,const等關鍵字,而不是char*, char[]的差別 12/09 20:54
→ atst2:在c/c++中,傳回local的reference是undefined的行為,不同編 12/09 20:55
→ atst2:譯器可能有不同的行為. 12/09 20:56
→ dou0228:我知道你想說啥,不過 return ch, compile 能過?? 12/09 22:17
打錯, 已經修正。
※ 編輯: descent 來自: 115.43.245.118 (12/09 22:57)
推 asleisureto:第一次看到指標指向常數的用法@@ 所以這邊的hello像 12/09 23:20
→ asleisureto:new一樣是存在heap而非stack? 12/09 23:20
推 littleshan:這種題目很基本耶...(被考這種題目我會生氣吧 XD 12/10 00:18
→ littleshan:hello和其它literal一樣 通常放在read only data 12/10 00:24
→ leiyan:我只會覺得用string就好了弄個容易有bug的東西來找麻煩 12/10 01:42
推 littleshan:因為很多人覺得C++太慢啊 科科 12/10 09:13
→ x000032001:那甚麼語言算是快的= =" 12/12 07:36
推 thinkniht:組合語言 12/13 20:59