[問題] linkedlist之傳遞問題

看板C_and_CPP作者時間9年前 (2015/05/24 16:21), 9年前編輯推噓9(906)
留言15則, 6人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VS2010 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) standard lib. 問題(Question): 我將結構的位址傳入副程式,卻無法在主程式使用 程式碼(Code):(請善用置底文網頁, 記得排版) //linklist.h struct list{ int num; struct list *nx; }; typedef struct list node; //main.c #include<stdlib.h> #include<stdio.h> void create(node *top, node *previous, node *current); int main(){ node *top,*previous,*current; top=previous=current=NULL; create(top,previous,current); printf("first data is %d\n",top->num); printf("second data is %d\n",top->nx->num); system("pause"); return 0; } void create(node *top, node *previous, node *current){ int i; for(i=0;i<3;i++){ current = (node *)malloc(sizeof(node)); current->nx=NULL; printf("Enter num"); scanf("%d",&current->num); if(top==NULL) top=NULL; else previous->nx=current; previous=current; } } 補充說明(Supplement): print出來的值都是NULL 怎麼會這樣呢?傳遞過去不是都是記憶體位置?理論上來說在主程式或是副程式修改都沒問題 是不是我哪邊忽略了?我才剛開始學資料串結,拜託幫幫我,別砲新手,謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.233.78.140 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1432455711.A.CCB.html

05/24 16:26, , 1F
你的create裡的指標只是外面的指標的挎貝
05/24 16:26, 1F
怎麼會呢? 我不是傳位址過去了?還是說我要怎麼改才對?? ※ 編輯: jacky1989 (118.233.78.140), 05/24/2015 16:26:54

05/24 16:29, , 2F
但是它們本身是存在不同地方的變數
05/24 16:29, 2F

05/24 16:30, , 3F
你的狀況要嘛用node**去操作,要嘛用node*&來操作
05/24 16:30, 3F

05/24 16:51, , 4F
main裡的top與create裡的top是不同的指標
05/24 16:51, 4F

05/24 16:53, , 5F
不是"傳位址",而是複製指標的值(指向的位址)給新的指標
05/24 16:53, 5F
感謝各位回答 我將top current previous定義在header理面,用extern來解決了 ※ 編輯: jacky1989 (118.233.78.140), 05/24/2015 17:00:44

05/24 17:22, , 6F
怎麼突然出現extern…XDDD
05/24 17:22, 6F

05/24 17:23, , 7F
看起來還是沒搞懂 XD
05/24 17:23, 7F

05/24 18:01, , 8F
你做的是傳值呼叫 create裡面的top跟main裡面top沒關係
05/24 18:01, 8F

05/24 18:04, , 9F
extern XDDD
05/24 18:04, 9F
我在header file理面宣告node *top,*current,*previous 然後主程式直接extern node *top,*current,*previous 就可以直接在副程式用了,但是改成不傳址過去 ※ 編輯: jacky1989 (118.233.78.140), 05/24/2015 18:07:14

05/24 18:12, , 10F
你原code錯在你其實是"傳值", 推文是教你怎麼改..
05/24 18:12, 10F

05/24 18:14, , 11F
這種改法如果有1000個linkedlist你要extern到什麼時候
05/24 18:14, 11F
是喔!!但是推文提出的double point我不太會用耶 有人可以給我一點example嗎? ※ 編輯: jacky1989 (118.233.78.140), 05/24/2015 18:17:46

05/24 18:34, , 12F
外面 func(&n),裡面 *n=... 這樣
05/24 18:34, 12F

05/24 18:35, , 13F
就把node*當成一個型態,node**就是該型態的指標
05/24 18:35, 13F

05/24 18:47, , 14F
請看置底13戒第13項 有生動的圖文解說
05/24 18:47, 14F
正在參考,感謝 ※ 編輯: jacky1989 (118.233.78.140), 05/24/2015 18:57:02

05/28 21:27, , 15F
有學過組語就知道怎麼回事了
05/28 21:27, 15F
文章代碼(AID): #1LOOeVpB (C_and_CPP)