看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): while內條件式無法成立 餵入的資料(Input): while(sort_list->data) 預期的正確結果(Expected Output): 當不輸入資料,直接按下ENTER鍵時應該跳出do while迴圈 錯誤結果(Wrong Output): do while行程無線迴圈 程式碼(Code):(請善用置底文網頁, 記得排版) 小弟欲輸入各個數字,並按下ENTER鍵後,離開程 typedef struct _list{ int data; struct _list *next; }list; int main(int argc,char *argv[]) { int input=0; char *buffer=(char *)malloc(5); list *sort_list; do{ list *sort_list=(list *)malloc(sizeof(list)); sort_list->next=NULL; printf("Please input your member to sort: "); fgets(buffer,5,stdin); sort_list->data=(atoi)(buffer); printf("%d\n",sort_list->data); } while (sort_list->data); free(buffer); free(sort_list); } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.115.119.128 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1431253151.A.9D3.html
vvrr: 用gcc 4.8.2在Ubuntu下執行是正常的@@ 05/10 18:44
vvrr: 順帶一提,這樣子如果輸入「0」的話也會跳出迴圈哦.. 05/10 18:44
longlongint: 對不起 我看不懂原po的程式 05/11 04:32
scwg: 在 do{ 裡面宣告的 list *sort_list 遮住了外面的定義, 選個 05/11 05:04
scwg: 不同的名字, 然後讀書看 linked list 怎麼插入元素 05/11 05:04
nobodyuse: 這是一個未完成的程式,主要是要以指標方式儲存資料 05/11 08:27
nobodyuse: do while 迴圈會多增加一個list *sort_list是因為gcc編 05/11 08:29
nobodyuse: 譯時會出現sort_list undeclared (first use in this 05/11 08:30
nobodyuse: function)的錯誤訊息,這是讓小弟感到奇怪的地方。 05/11 08:31
nobodyuse: 但是列印sort_list->data,不論是按下ENTER與0其顯示值 05/11 08:32
nobodyuse: 都是0,只是納悶為何跳不出迴圈? 05/11 08:33
nobodyuse: 另外,若不以指標方式而修改宣告為list sort_list,並 05/11 08:34
nobodyuse: 將所有的sort_list->data改為sort_list.data則可正常執 05/11 08:35
nobodyuse: 行,可以跳脫do while迴圈,小弟也曾懷疑是否以指標方 05/11 08:36
nobodyuse: 在迴圈中print出sort_list->data值確定為0,因此不知 05/11 08:38
nobodyuse: 跳不出迴圈,不知小弟的觀念上哪裡出了問題?感謝各位 05/11 08:39
qsort: 你的compile是哪一個? 05/11 09:56
qsort: do while的sort_list scope,只限在do while內 05/11 09:56
qsort: 而while (sort_list->data) 的sort_list, 其實是用buffer下 05/11 09:57
qsort: 面的那一個,也就是一個uninitialized sort_list 05/11 09:58
qsort: http://ideone.com/hYmzpU 請看記憶體,不是同一塊 05/11 10:04
vvrr: 0rz我第一次compile的時候也有出現那個錯誤 修掉後忘記了.. 05/11 11:05
vvrr: 沒注意到就推文說沒有問題@@...抱歉 05/11 11:06
nobodyuse: 感謝vvrr協助解決... 05/11 11:50
nobodyuse: 將do while內部list *sort_list=(list *)malloc(xxxx) 05/11 11:51
nobodyuse: 拿掉list *即可正常work...感謝各位!! 05/11 11:51