c - 从函数返回指针

标签 c memory-management malloc

这是引用这个问题: Why is a pointer to pointer needed to allocate memory in this function?

问题的答案解释了为什么这不起作用:

void three(int * p)
{
    p = (int *) malloc(sizeof(int));
    *p = 3;
}

void main()
{
    int *p = 0;
    three(p);
    printf("%d", *p);
}

...但这有效:

void three(int ** p)
{
    *p = (int *) malloc(sizeof(int));
    **p = 3;
}

void main()
{
    int *p = 0;
    three(&p);
    printf("%d", *p);
}

这也有效,通过从函数返回一个指针。这是为什么?

int* three(int * p)
{
    p = (int *) malloc(sizeof(int));
    *p = 3;
    return p;
}

void main()
{
    int *p = 0;
    p = three(p);
    printf("%d", *p);
}

最佳答案

int* three(int * p) 
    {
        p = (int *) malloc(sizeof(int));
        *p=3;
        return p;
    }

因为在这里您要返回指针 p副本,并且该指针现在指向有效内存,其中包含值 3。

您最初将 p 的一个副本 作为参数传入,因此您不是在更改传入的那个,而是一个副本。然后您返回该副本并分配它。

从评论来看,这是一个非常有效的观点,这也同样有效:

 int* three() 
        {
           //no need to pass anything in. Just return it.
            int * p = (int *) malloc(sizeof(int));
            *p=3;
            return p;
        }

关于c - 从函数返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496346/

相关文章:

c - 创建一个没有 malloc 的链表

c - getaddrinfo 中的 malloc 校验和不正确

memory-management - GPU 访问系统 RAM

c - 使用 Malloc (char & int) 分配内存

c++ - 一个有效的程序被 man7.org 宣布为无效

c - 这两件事有什么区别

javascript - 你用什么来监控 Internet Explorer 中的 jscript 内存使用情况

c++ - 每次我使用 placement new 分配时都会隐式调用析构函数

c - 公开或不公开 API

c++ - C 或 C++ 或 WinApi 中是否有任何函数可以创建目录,包括指定路径中所有不存在的目录?