C 语言里,把一个指针传入一个函数内赋值,那个函数结束后,对传入的指针的变量的改动不会回到 main 函数中吗?这种设计有什么考虑吗?该怎么解决呢?

2017-04-22 13:49:28 +08:00
 Newyorkcity
#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);
}

两次输出的内容是不一样的,在 test 里已经变成了一个有意义的地址,但在 main 中再次打印又变成了一串 0 。
谢谢
1689 次点击
所在节点    问与答
8 条回复
wevsty
2017-04-22 13:55:46 +08:00
C 是按值传递的。
这个例子里面 test 函数里面的 p 是 main 函数里面指针 p 的拷贝,所以 test 里面对指针修改不影响 main 函数里面的指针。
如果想在函数里修改传入的指针,请传入指向指针的指针。
disposablexyz
2017-04-22 13:57:42 +08:00
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
northisland
2017-04-22 14:12:51 +08:00
指针存储的是内存地址偏移量,

你这 p = &i;耍的都是指针本身,却问是指针对应内存(*p)相关的问题~~~~

再看看教科书吧
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);
}
```

用二级指针,这样才是可行的做法。
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 )什么的简直是太吓人了
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
lany
2017-04-22 14:29:34 +08:00
@northisland 对头,楼主成功上演了一次野指针的 printf
Perry
2017-04-22 14:44:46 +08:00
test 的 int *p 是被 copy 过的
解决方法是 int **p 然后 *p = &i

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/356620

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX