[問題] linklist add時出現怪問題(已解決)

看板C_and_CPP (C/C++)作者 (okla)時間12年前 (2013/10/03 22:35), 編輯推噓0(0011)
留言11則, 3人參與, 最新討論串1/1
開發平台(Platform):GCC (Ex: VC++, GCC, Linux, ...) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question):現在問題變成 add函數裡面 top->ptr=NULL 這行註解掉跑display函數 就會出現無窮迴圈.. 不太懂為什麼以邏輯角度 這一行有沒有都無所謂不是嗎@@? 懇請大大幫忙解答 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output):segmentation fault 程式碼(Code): #include<stdlib.h> #include<stdio.h> typedef struct node{ int data; struct node *ptr; }node; node *add(node*, int); node *delete(node*); void display(node*); int isempty(node*); node *first; int main(void){ node *top; top = NULL; int s; while(s != 4){ printf("輸入操作選項:(1)insert node;(2)delete node;(3)display(4)no operation\n"); scanf("%d",&s); switch(s) { case 1: printf("輸入item\n"); int num; scanf("%d", &num); top = add(top, num); break; case 2: top = delete(top); break; case 3: display(first); break; default: break; } } return 0; } node *add(node *top, int item){ node *temp; temp = (node*)malloc(sizeof(node)); if(top==NULL){ temp->ptr==NULL; temp->data=item; first=temp; top=temp; return top; } temp->ptr = top->ptr; temp->data = item; top->ptr = temp; top=temp; //top->ptr=NULL; return top; } node *delete(node *top) { if(isempty(top)) printf("linklis is empty!\n"); else { int item; node *temp = first; while (temp->ptr != top) { temp = temp->ptr; } temp->ptr = top->ptr; item = top->data; free(top); printf("delete node's item :%d\n",item); return temp; } return NULL; } void display(node *first){ node *temp; temp = first; int i = 1; while(temp != NULL) { printf("linklist 第%d個item:%d\n",i, temp->data); i++; temp = temp->ptr; } } int isempty(node *top){ if(top==NULL) return 1; else return 0; } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.115.51.232 ※ 編輯: okokokla2001 來自: 140.115.51.232 (10/03 22:40)

10/03 22:57, , 1F
add的時候如果top還是NULL怎麼辦?
10/03 22:57, 1F

10/03 23:04, , 2F
如果top為NULL 它的ptr與data不是全部為NULL嗎?
10/03 23:04, 2F

10/03 23:09, , 3F
如果你有一個無效的地址,這個地址裡頭住的是誰?
10/03 23:09, 3F

10/03 23:19, , 4F
抱歉還是有點不太懂 所以是我不能直接去指NULL內的東
10/03 23:19, 4F

10/03 23:19, , 5F
西的意思@@?
10/03 23:19, 5F
※ 編輯: okokokla2001 來自: 140.115.51.232 (10/03 23:23)

10/03 23:26, , 6F
我在想下好了
10/03 23:26, 6F

10/04 00:28, , 7F
null pointer不是空白,是「沒有東西」
10/04 00:28, 7F

10/04 00:29, , 8F
你不能讀或寫「沒有東西」裡頭的東西
10/04 00:29, 8F

10/04 00:33, , 9F
恩恩 我有換方法寫了 但有一個地方有疑惑能幫忙解惑
10/04 00:33, 9F

10/04 00:34, , 10F
嗎? 我回附貼文
10/04 00:34, 10F

10/04 11:46, , 11F
你可以先參考課本的範本 不要自己硬打
10/04 11:46, 11F
※ 編輯: okokokla2001 來自: 140.115.51.232 (10/04 14:58) ※ 編輯: okokokla2001 來自: 140.115.51.232 (10/04 15:11)
文章代碼(AID): #1IJO2s1I (C_and_CPP)
文章代碼(AID): #1IJO2s1I (C_and_CPP)