看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) C 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) string.h 問題(Question): 將標準輸入的各行字串照字母順序排序 可是在執行到一半的時候就發生錯誤了 餵入的資料(Input): candy apple cat banana 預期的正確結果(Expected Output): apple banana candy cat 錯誤結果(Wrong Output): 發生錯誤,執行失敗 程式碼(Code):(請善用置底文網頁, 記得排版) http://ideone.com/3T4ZPL 補充說明(Supplement): 我自己試的時候發現 好像是strcmp那邊發生了問題 不知道是不是strcmp不能這樣用 我剛接觸程式不到3個月,可能犯下很多低級錯誤 還望指教!感謝~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.215.66.203 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1449741756.A.809.html ※ 編輯: alen0303 (49.215.66.203), 12/10/2015 18:05:56
LPH66: strdup 的問題, 它新抓的空間只會剛好存放它複製的字串 12/10 18:12
LPH66: 你在交換時放一個過長的字串進去就爆了 12/10 18:12
LPH66: 比較簡單的做法是不用 strdup, 把 lines 宣告成 char 二維 12/10 18:13
LPH66: 變成像 char lines[MAXCOUNT][MAXSTRLEN]; 12/10 18:13
LPH66: 然後 fgets 就可以直接丟進 lines[i] 裡面去 12/10 18:13
LPH66: 這樣交換時保證你有空間可以放新字串 12/10 18:14
LPH66: 另外使用 strdup 還有一個問題是你得手動 free 它 12/10 18:14
LPH66: 這個比起你自己 malloc 來的東西還更容易忘記 free 12/10 18:15
哦哦 大概懂意思了 感謝!! ※ 編輯: alen0303 (49.215.66.203), 12/10/2015 18:18:52
fightforlive: 推 12/10 22:06
stupid0319: 我以為只要宣告一個char陣列來記錄排名就好了 12/11 13:23