[問題] 如何讓多個指標指向同一個struct記憶區塊

看板C_and_CPP作者 (larkes)時間13年前 (2012/04/15 21:32), 編輯推噓1(106)
留言7則, 4人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) C語言, editor是Dev C++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) stdio.h stdlib,h 問題(Question): struct list *first = NULL; struct list *second = NULL; first = second; second = (struct list *)malloc(sizeof(struct list)); second->next = NULL; if(first == NULL) printf("first is NULL \n"); 執行結果是:first is NULL 從這可以看出first只是擁有跟second一模一樣的內容, 但是卻沒有跟second共用一個記憶區塊. 請問....如何在不使用function的情況下, 撰寫code,讓first跟second共用一個記憶區塊呢? 因為我希望second被修改時, first也跟著被修改. 預期的正確結果(Expected Output): first跟second指向同一個記憶區塊. 還麻煩請指教一下, 謝謝~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.120.179.172

04/15 21:37, , 1F
你的first = second;跟下一行交換...
04/15 21:37, 1F
※ 編輯: larkes 來自: 59.120.179.172 (04/15 21:48)

04/15 21:48, , 2F
謝謝指教~
04/15 21:48, 2F

04/15 21:52, , 3F
步驟有點反了,1st先allocate後,再將 1st assigned to 2nd.
04/15 21:52, 3F

04/15 21:53, , 4F
嗯~謝謝您
04/15 21:53, 4F

04/17 23:47, , 5F
把first設為pointer to pointer再設定為second
04/17 23:47, 5F

04/21 12:05, , 6F
嗯~謝謝︿︿
04/21 12:05, 6F

04/21 12:06, , 7F
是設成這樣子嗎:struct list **first = NULL;
04/21 12:06, 7F
文章代碼(AID): #1FYiu4xV (C_and_CPP)
文章代碼(AID): #1FYiu4xV (C_and_CPP)