作者f422661 (恩恩)
看板C_and_CPP
標題[問題] linklist製作stack
時間Mon Dec 14 00:27:10 2015
開發平台(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
→ remizu: return的top沒有接住 還有十三戒之13 12/14 00:40
→ OPIV: 正確結果是5、3吧 12/14 00:51
推 hl4: push(&top) 12/14 01:35
推 tsoahans: call by value/reference的問題 12/14 01:41
感謝大大回答,想另請問參數是傳指標不算call by pointer嗎?
※ 編輯: f422661 (163.25.119.56), 12/14/2015 02:35:40
推 OPIV: 是 call by pointer 沒錯,但是因為你動到 pointer 本身的 12/14 03:09
→ OPIV: 值了,所以要 pass pointer to pointer 才行 12/14 03:09
推 LPH66: 所以說 cbp 這講法會讓人混淆就是這樣 12/14 03:38
→ LPH66: 你要改動一個變數就傳它的位址進去即可, 不論這變數是什麼 12/14 03:39
推 stupid0319: 不才認為typedef struct node *Node;這樣寫比較好 12/14 07:44
推 stupid0319: 你的stack的next應該是指向上一個,寫next有點怪怪的 12/14 08:01
感謝各位大大回答,小弟知道錯在哪裡了..
※ 編輯: f422661 (163.25.119.57), 12/14/2015 09:48:33