@AKE 2019-09-19 11:42 采纳率: 0%
浏览 193
已采纳

为什么会输出P空?我在test中赋空间为啥没有用?

#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

  • 写回答

2条回答 默认 最新

  • alongname 2019-09-19 14:00
    关注

    你这样传的是p所指向内容的指针,*p 能够修改p所指向的内容。

    如果要修改指针本身的内容,就要传指针的指针。

    要在局部函数里面修改谁,就传谁的指针或引用。

    void test(int **p)
    {
        //此时 p 为 指针p的地址,*p 为p指向的内容的地址,**p为p指向的内容
        *p = (int*)malloc(sizeof(int));
    }
    
    test(&p); //把指针自己的地址传进去
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?