[問題] 不太懂錯在哪 想請問一下指標的問題

看板C_and_CPP作者 (阿吉)時間15年前 (2009/09/01 13:53), 編輯推噓6(6013)
留言19則, 4人參與, 最新討論串1/1
我不想要主程式裡直接宣告一個空間給*a 跟 *b 想要在副程式裡再宣告空間給它 請問一下大家我這樣寫哪邊有問題 我實在不太瞭解...謝謝大家了 #include <iostream> #include <conio.h> #include <string.h> using namespace std; struct node { string name; node *next; }; void get_data(struct node *); int main() { node *a,*b,c; get_data(a); get_data(b); cout << "a=" << a->name <<endl; cout << "b=" << b->name <<endl; delete a; delete b; getch(); return 0; } void get_data(struct node *data) { node *tmp; tmp = new node; cout << "name="; cin >> tmp->name; tmp->next=NULL; data=tmp; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 134.208.2.154

09/01 14:00, , 1F
data指標指向新new出來的空間 但是a,b並沒有
09/01 14:00, 1F

09/01 14:01, , 2F
請用call by reference..
09/01 14:01, 2F

09/01 14:02, , 3F
或者是把tmp = new node; 改成 data = new node;
09/01 14:02, 3F

09/01 14:03, , 4F
不然就是傳a, b的address下去, new完data存會a, b去....
09/01 14:03, 4F

09/01 14:04, , 5F
很典型的類swap傳參數沒傳對的問題....:)
09/01 14:04, 5F

09/01 14:06, , 6F
3F那樣做跟他現在寫的似乎沒差吧??那樣做應該不行@_@"
09/01 14:06, 6F

09/01 14:08, , 7F
三樓那個我確定不行 因為我有試過了 還是我的寫法不正確
09/01 14:08, 7F

09/01 14:08, , 8F
要傳struct node *& data進去@@
09/01 14:08, 8F

09/01 14:09, , 9F
VictorTom 傳AB 的ADDRESS 可以明確一點嘛 有EXAMPLE可以
09/01 14:09, 9F

09/01 14:09, , 10F
貼上來給我看一下嘛 因為我真的沒頭序了
09/01 14:09, 10F

09/01 14:10, , 11F
你把參數改成struct node* &data再試試看吧
09/01 14:10, 11F

09/01 14:15, , 12F
OK了 +& 這樣是對的 謝謝大家了 我再看看我是哪邊的問題^^
09/01 14:15, 12F

09/01 14:16, , 13F
就是call by value/call by reference的問題啊...
09/01 14:16, 13F

09/01 14:17, , 14F
struct node* 是call by value to pointer..
09/01 14:17, 14F

09/01 14:17, , 15F
struct node*& 是call by reference to pointer
09/01 14:17, 15F

09/01 14:19, , 16F
我是說我要更去瞭解 我是哪邊不懂啦^^" 這須要一點內化^^
09/01 14:19, 16F

09/02 09:01, , 17F
你要改變的是pointer,但你給的位址只是pointer所指向的
09/02 09:01, 17F

09/02 09:03, , 18F
node,這樣你只能改變node裡的資料,卻改不了pointer所指
09/02 09:03, 18F

09/02 09:03, , 19F
向的記憶體位址
09/02 09:03, 19F
文章代碼(AID): #1AdBRGJ2 (C_and_CPP)