双指针不会在函数中获得malloc [英] Double pointer doesn't get malloc'd in function

查看:83
本文介绍了双指针不会在函数中获得malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在C语言中工作,并且在一个函数中有一个 int ** ,该函数在另一个函数中进行了修改.运行此问题时遇到了SegFault,因此我决定使用 gdb 对其进行调试.我发现内存从未分配给该数组.我的功能是这样的

So I'm working in C and I have an int ** inside of one function that is modified within another function. I was getting a SegFault when I was running this problem so I decided to debug it with gdb. What I found was that memory was never allocated to this array. My functions are like this

void declarer()
{
    int ** a;
    alocator(a, 4, 5);
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 5; j++)
            printf("%d\n", a[i][j]);
}

void alocator(int ** a, int b, int c)
{
    a = (int **)malloc(sizeof(int *) * b);
    for (int i = 0; i < b; i++) {
        a[i] = (int *)malloc(sizeof(int) * c);
        for (int j = 0; j < c; j++)
            a[i][j] = j;
    }
}

当我在 alocator(a,4,5)行之后的断点运行 gdb 时(在程序段错误之前),并且我写 pa ,我得到 $ 1 =(int **)0x0 ,这表明 a 位于地址 0x0 上,并且没有为其分配内存.为什么 alocator 不为其分配内存,我如何获得 alocator 来为 a 分配内存?

When I run gdb with a breakpoint after the line alocator(a, 4, 5) (before the program segfaults), and I write p a, I get $1 = (int **) 0x0 which shows that a is at address 0x0 and has no memory allocated for it. Why did alocator not allocate memory to it, and how can I get alocator to allocate memory to a?

推荐答案

由于要按值传递 ** a ,因此必须将其作为指针传递.因此,请使用三重指针:

Because you are passing **a by value, you have to pass it as pointer. So use a triple pointer:

void declarer()
{
    int **a;
    alocator(&a, 4, 5);
    ...
}

void alocator(int ***a, int b, int c)
{
    *a = (int **)malloc(sizeof(int *) * b);
    ...

这篇关于双指针不会在函数中获得malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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