#include <stdio.h>
#include <malloc.h>
void test(int *p)
{
p=(int*)malloc(sizeof(int));
}
int main()
{
int *p=NULL;
test(p);
if (p==NULL)
printf("p空");
return 0;
}
我在test中赋空间 为什么在main中显示p为kong
#include <stdio.h>
#include <malloc.h>
void test(int *p)
{
p=(int*)malloc(sizeof(int));
}
int main()
{
int *p=NULL;
test(p);
if (p==NULL)
printf("p空");
return 0;
}
我在test中赋空间 为什么在main中显示p为kong
你这样传的是p所指向内容的指针,*p 能够修改p所指向的内容。
如果要修改指针本身的内容,就要传指针的指针。
要在局部函数里面修改谁,就传谁的指针或引用。
void test(int **p)
{
//此时 p 为 指针p的地址,*p 为p指向的内容的地址,**p为p指向的内容
*p = (int*)malloc(sizeof(int));
}
test(&p); //把指针自己的地址传进去