看板 Soft_Job 關於我們 聯絡資訊
裡頭提到很多公司考的題目, 我認為拿來當題庫練習還不錯, 全部搞懂的話應該可以應付大多數公司的筆試。 討論其中一題: char *a(){ char ca[]="hello"; return ch; } 這樣有什麼問題。 大概就是: 放在 stack 裡, 在 return 時, stack 會被清掉, 所以無法預期 c[] 的值還會是 "hello"。 書中提出可用 char *c="hello"; 改善。 書中有解釋, 我覺得很有趣, 也翻了一下 The C Programming Language, 不過沒看到說明這一差異, 可能我沒找到。 想知道書上解釋的原因, 轉成組合語言就清楚多了。 由於程式碼較長, 分享在 blog 上。 http://descent-incoming.blogspot.com/2011/12/c-runtime-array-vs-pointer.html -- 死, 是生命最偉大的發明。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 115.43.245.118
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