看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Windows7 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) dev c++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 小弟我最近開始讀data structure,除了讀理論也開始用code實作 我寫了一個push function 傳入一個結構指標跟一筆data 在function 裡面新增一個結構指標存push的資料 新結構指標的next location為傳入的結構指標 再讓傳入的結構指標等於那個新結構指標 預期應該用top function輸出的資料為我push進去的資料 結果跟push之前的資料一樣 測試了一下記憶體位置 push之前跟之後的記憶體位置一樣 (說的可能有點不清楚,看程式碼應該比較好了解) 程式碼(Code):(請善用置底文網頁, 記得排版) #include<iostream> using namespace std; struct Node { int data; struct Node* next; }; typedef struct Node STACK; STACK* create(int); void push(STACK*,int); void pop(STACK*); void top(STACK*); int main() { STACK* sta=create(50); cout<<sta<<endl; push(sta,100); cout<<sta<<endl; return 0; } STACK* create(int data) { STACK* tmp= new STACK; tmp->data=data; tmp->next=NULL; return tmp; } void push(STACK* tmp, int data) { STACK* use=new STACK; use->data=data; use->next=tmp; tmp=use; } void pop(STACK* tmp) { STACK* use=new STACK; use=tmp; tmp=tmp->next; } void top(STACK* tmp) { cout<<tmp->data<<endl; } 補充說明(Supplement): -- 放棄是最簡單的 也是最無趣的 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.255.164.250 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1505226419.A.64F.html ※ 編輯: xiefengan (111.255.164.250), 09/12/2017 22:33:42
bluesoul: push 應該傳pointer reference09/12 22:48
我有用過pointer reference 但是想說如果遇到用c實作怎麼辦 我想說我傳入push的方式應該是 call by address,不過看起來好像不是
james732: 不知道為什麼看到class+typedef就會覺得好煩躁(?)09/12 22:52
james732: .....明明是structure,我眼殘了請無視二樓的白癡推文09/12 22:52
※ 編輯: xiefengan (111.255.164.250), 09/12/2017 23:00:15
Raymond0710: 傳兩個星號 **09/12 23:29
outofyou: call by value所以tmp參數當然不會變。要用樓上解法。09/12 23:38
school4303: 傳指標的指標?09/13 16:23
謝謝樓上幾位,看來我對指標還不夠熟悉
Lipraxde: return一個新的stack point回來也可以吧?09/13 16:25
試過應該可以,只是想試試別種寫法 ※ 編輯: xiefengan (111.255.46.121), 09/13/2017 17:19:00