小编PM.*_*PM.的帖子

使用malloc分配的内存不会在函数范围之外保留?

嗨,

我对C的malloc函数有点新,但据我所知,它应该将值存储在堆中,因此您可以使用来自原始范围之外的指针来引用它.我创建了一个应该执行此操作的测试程序,但在运行程序后,我一直得到值0.我究竟做错了什么?

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

int f1(int *b) {
    b = malloc(sizeof(int));
    *b = 5;
}

int main(void) {
    int *a;
    f1(a);
    printf("%d\n", a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c malloc

13
推荐指数
4
解决办法
1万
查看次数

标签 统计

c ×1

malloc ×1