为什么我在函数中分配了指针内存,但它也是NULL?

HiM*_*ing 2 c

代码使我困惑.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

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

int main()
{
    int *p = NULL;

    create_int(p);

    assert(p != NULL);  /* failed. why? I've allocated memory for it. */

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ken*_*nan 7

您没有从函数返回指针值.尝试:

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

int main() {
     int *p = NULL;      
     create_int(&p);
     assert(p != NULL);  /* failed. why? I've allocated memory for it. */
     return 0;
} 
Run Code Online (Sandbox Code Playgroud)

  • @HiMing:因为``create_int`函数中的`p`是与`main`函数中的`p`完全不同的变量.它最初只具有相同的值,因为您将main中的值作为参数传递.更改`create_int`中`p`的值对`main`中的`p`的值没有影响,它仍然是一个空指针. (4认同)
  • 或者更好,`int*create_int(void){return malloc(sizeof(int)); }`,然后只是`int*p = create_int();`. (2认同)