#include<stdio.h> #include<stdlib.h> void test(int *p); int main(){ int *p = NULL; test(p); printf("in main, p = %p\n",p); return 0; } void test(int *p){ int i=1; p = &i; printf("in test, p = %p\n",p); }
1 wevsty 2017-04-22 13:55:46 +08:00 ![]() C 是按值传递的。 这个例子里面 test 函数里面的 p 是 main 函数里面指针 p 的拷贝,所以 test 里面对指针修改不影响 main 函数里面的指针。 如果想在函数里修改传入的指针,请传入指向指针的指针。 |
2 disposablexyz 2017-04-22 13:57:42 +08:00 via iPhone You are given a pointer to an int, you want to change the int, not the pointer. So you should do *p = i; *BTW, int *p = NULL; will cause segmentation fault |
![]() | 3 northisland 2017-04-22 14:12:51 +08:00 指针存储的是内存地址偏移量, 你这 p = &i;耍的都是指针本身,却问是指针对应内存(*p)相关的问题~~~~ 再看看教科书吧 |
![]() | 4 ipwx 2017-04-22 14:16:07 +08:00 首先, p = &i 出了 test 之后就是无意义的地址了。 其次,如果你想要改变 传入指针: ``` void test(int **p) { *p = (int*)malloc(sizeof(int)); } int main() { int *p = NULL; test(&p); } ``` 用二级指针,这样才是可行的做法。 |
![]() | 5 northisland 2017-04-22 14:16:22 +08:00 #include<stdio.h> #include<stdlib.h> int ga=89; int gb=86; void test(int *p); int main(){ int *p = &ga; test(p); printf("in main, p = %d\n",*p); return 0; } void test(int *p){ p = &gb; printf("in test, p = %d\n",*p); } 这样就对了。。。野指针( stray pointer )什么的简直是太吓人了 |
![]() | 6 northisland 2017-04-22 14:21:39 +08:00 #include<stdio.h> #include<stdlib.h> int ga=89; int gb=86; void test(int *p); int main(){ int *p = &ga; test(p); printf("in main, p = %d\n",*p); return 0; } void test(int *p){ *p = gb; printf("in test, p = %d\n",*p); } // 头晕,这个才对,,,弄不懂指针千万别写 C 坑人。。。 // ./test1 // in test, p = 86 // in main, p = 86 |
![]() | 7 lany 2017-04-22 14:29:34 +08:00 @northisland 对头,楼主成功上演了一次野指针的 printf |
![]() | 8 Perry 2017-04-22 14:44:46 +08:00 via iPhone test 的 int *p 是被 copy 过的 解决方法是 int **p 然后 *p = &i |