作者gozule (好冷啊~~)
站內C_and_CPP
標題[問題] 請教關於pointer的問題
時間Sat Mar 7 00:31:32 2009
我最近在寫程式的時候,遇到了一個關於指標的問題,問題簡化後如下:
struct node{
int value;
};
typedef struct node* nodeptr;
void change(nodeptr ptr1, nodeptr ptr2){
printf("in fun, before change ptr1 = %p, ptr2 = %p\n", ptr1, ptr2);
nodeptr temp = ptr1; ptr1 = ptr2; ptr2 = temp;
printf("in fun, after change ptr1 = %p, ptr2 = %p\n", ptr1, ptr2);
}
int main(){
nodeptr ptr1 = (nodeptr)malloc(sizeof(struct node));
nodeptr ptr2 = (nodeptr)malloc(sizeof(struct node));
printf("before function call ptr1 address = %p\n", ptr1);
printf("before function call ptr2 address = %p\n", ptr2);
change(ptr1, ptr2);
printf("after function call ptr1 address = %p\n", ptr1);
printf("after function call ptr2 address = %p\n", ptr2);
free(ptr1);
free(ptr2);
return EXIT_SUCCESS;
}
結果:
before function call ptr1 address = 003E2468
before function call ptr2 address = 003E24D0
in fun, before change ptr1 = 003E2468, ptr2 = 003E24D0
in fun, after change ptr1 = 003E24D0, ptr2 = 003E2468
after function call ptr1 address = 003E2468
after function call ptr2 address = 003E24D0
我想問的是為何指標在function內已經重新指向不同的變數,
為什麼在返回main之後指標又指向呼叫function前的位址?
在不使用全域變數下,該如何修改以得到我想要的行為?
懇請高手指教,謝謝:)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.187.32.168
※ 編輯: gozule 來自: 218.187.32.168 (03/07 00:33)
※ 編輯: gozule 來自: 218.187.32.168 (03/07 00:34)
推 sawang:這個,簡單說就是call by value,所以函數沒改變到原值 03/07 01:07
→ sawang:你可以使用call by address的方式,就OK了 03/07 01:07
→ jaw109:沒有call by address 03/07 13:40