作者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)
1F:推 sawang:这个,简单说就是call by value,所以函数没改变到原值 03/07 01:07
2F:→ sawang:你可以使用call by address的方式,就OK了 03/07 01:07
3F:→ jaw109:没有call by address 03/07 13:40