[問題] linklist製作stack

看板C_and_CPP (C/C++)作者 (恩恩)時間10年前 (2015/12/14 00:27), 10年前編輯推噓6(604)
留言10則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): stack push 失敗 明明用除錯看push return top 都是成功把值放到stack裡的 結果一return回main function top又是指向null而不是我push進去的node 求各位大大幫忙指點問題了.. 餵入的資料(Input): 3 ,5 預期的正確結果(Expected Output): 3,5 錯誤結果(Wrong Output):程式碼(Code):(請善用置底文網頁, 記得排版) struct node { int data; struct node *next; }; typedef struct node Node; Node* push(Node* top, int item); void show(Node* a); int _tmain(int argc, _TCHAR* argv[]) { Node *top=NULL; push(top,3); push(top,5); show(top); return 0; } Node* push(Node* top, int item) { Node* temp; temp = (Node*) malloc(sizeof(Node)); temp->data = item; temp->next = top; top = temp; return top; } void show(Node* top) { Node* tmpnode; tmpnode = top; printf("\n堆疊內容:"); while(tmpnode != NULL) { printf("%d ", tmpnode->data); tmpnode = tmpnode->next; } } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 163.25.119.56 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1450024033.A.B08.html

12/14 00:40, , 1F
return的top沒有接住 還有十三戒之13
12/14 00:40, 1F

12/14 00:51, , 2F
正確結果是5、3吧
12/14 00:51, 2F

12/14 01:35, , 3F
push(&top)
12/14 01:35, 3F

12/14 01:41, , 4F
call by value/reference的問題
12/14 01:41, 4F
感謝大大回答,想另請問參數是傳指標不算call by pointer嗎? ※ 編輯: f422661 (163.25.119.56), 12/14/2015 02:35:40

12/14 03:09, , 5F
是 call by pointer 沒錯,但是因為你動到 pointer 本身的
12/14 03:09, 5F

12/14 03:09, , 6F
值了,所以要 pass pointer to pointer 才行
12/14 03:09, 6F

12/14 03:38, , 7F
所以說 cbp 這講法會讓人混淆就是這樣
12/14 03:38, 7F

12/14 03:39, , 8F
你要改動一個變數就傳它的位址進去即可, 不論這變數是什麼
12/14 03:39, 8F

12/14 07:44, , 9F
不才認為typedef struct node *Node;這樣寫比較好
12/14 07:44, 9F

12/14 08:01, , 10F
你的stack的next應該是指向上一個,寫next有點怪怪的
12/14 08:01, 10F
感謝各位大大回答,小弟知道錯在哪裡了.. ※ 編輯: f422661 (163.25.119.57), 12/14/2015 09:48:33
文章代碼(AID): #1MRPnXi8 (C_and_CPP)
文章代碼(AID): #1MRPnXi8 (C_and_CPP)