内存使用malloc分配不坚持功能以外范围? [英] Memory allocated with malloc does not persist outside function scope?

查看:164
本文介绍了内存使用malloc分配不坚持功能以外范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点新的C的malloc函数,但是从我知道它应该值存储在堆中,这样你就可以从原来的范围之外的指针引用它。我创建了应该做一个测试程序,但我不断收到值0,运行该程序后。我在做什么错了?

I'm a bit new to C's malloc function, but from what I know it should store the value in the heap, so you can reference it with a pointer from outside the original scope. I created a test program that is supposed to do this but I keep getting the value 0, after running the program. What am I doing wrong?

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

int main() {
 int * a;
 f1(a);
 printf("%d\n", a);
 return 0;
}

推荐答案

是的! A 按值传递使指针 B 函数 F1 将本地..
要么返回 B

Yes! a is passed by value so the pointer b in function f1 will be local.. either return b,

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

int main() {
    int * a;
    a = f1();
    printf("%d\n", *a);
    // keep it clean : 
    free(a);
    return 0;
}

或通过 A 的地址

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

int main() {
    int * a;
    f1(&a);
    printf("%d\n", *a);
    // keep it clean : 
    free(a);
    return 0;
}

这篇关于内存使用malloc分配不坚持功能以外范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆