为什么我不能在函数中分配一个点。正如您在以下代码中注意到的那样。函数返回后,我无法分配指向正确地址的指针 p1。但是使用全局指针*p,我可以存储地址信息。
#include <stdio.h>
#include <stdlib.h>
int *p = NULL;
void test(int * pt1, int**pt2){
p = (int*)malloc(sizeof(int));
pt1 = p;
*pt2 = p;
printf("p points to %p\n", p);
printf("pt1 points to %p\n", pt1);
printf("pt2 points to %p\n", *pt2);
}
int main(void) {
int *p1 = NULL;
int *p2 = NULL;
printf("p points to %p\n", p);
printf("p1 points to %p\n", p1);
printf("p2 points to %p\n", p2);
test(p1, &p2);
printf("p points to %p\n", p);
printf("p1 points to %p\n", p1);
printf("p2 points to %p\n", p2);
return 0;
}
输出:
p points to (nil)
p1 points to (nil)
p2 points to (nil)
p points to 0x8acb008
pt1 points to 0x8acb008
pt2 points to 0x8acb008
p points to 0x8acb008
p1 points to (nil)
p2 points to 0x8acb008