c - 返回 main 时内存分配不是 "hold"

标签 c arrays pointers void-pointers

我有一个家庭作业,我需要在其中分配内存给一个指向指针数组 (pNode**) 的指针。 下面是接收指针数组的数组的函数,并为其分配内存以及内部所有相关的指针和数据。

简而言之,函数应该为指向 Node 指针数组的指针分配内存。

**注意:我已经从函数中删除了与我的问题无关的某些元素。 函数 newGNode 为 Node 结构体分配内存

int getChildren(pNode** childrenNodes)
{
    *childrenNodes = (pNode*)malloc(sizeof(pNode));
    for (int i = 0; i < NUM_OF_CHILDREN; i++)
    {
        childrenNodes[i] = (pNode *)newGNode();
    }
    return numOfChildren;
}

这是我在主函数中调用它的方式:

int main()
{
    pNode * ng = NULL;
    int test = getChildren(&ng);

}

无论我尝试做什么,我似乎都无法在主函数中“坚持”分配。在 getChildren 函数中,我可以在调试器中看到内存已按照我的需要精确分配。然而,当函数返回到 main 时,ng 指针似乎已损坏,因为调试器告诉我它无法读取内存。

我在网上搜索并尝试了不同的方法,但似乎都不起作用。有谁知道为什么这不能按预期工作?我猜内存分配中的某些东西是错误的,但似乎无法弄清楚是什么。

Here有一个问题和我的很相似,但它并没有真正帮助我

谢谢!

最佳答案

1) 你用两个参数调用 getChildren(),但它只需要一个参数:

int getChildren(pNode** childrenNodes)

2) 您想要一个数组,但为单个 pNode 保留空间:

*childrenNodes = (pNode*)malloc(sizeof(pNode));

更改为

*childrenNodes = malloc(sizeof(pNode) * NUM_OF_CHILDREN); /* Don't cast malloc */

编辑:

看来你想要一个指针数组,那么ng必须声明为:

pNode **ng = NULL; /* pointer to pointer */

你需要 3 个间接层来接收 ng:

int getChildren(pNode ***childrenNodes)

并为指针数组保留空间:

*childrenNodes = malloc(sizeof(pNode *) * NUM_OF_CHILDREN);

int 示例:

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

int arr[] = {1, 2};

void func(int ***p)
{
    *p = malloc(sizeof(int *) * 2);
    (*p)[0] = &arr[0];
    (*p)[1] = &arr[1];
}

int main(void)
{
    int **p;

    func(&p);
    printf("%d %d\n", *p[0], *p[1]);
    free(p);
    return 0;
}

但是 *** 被认为是糟糕的风格,而是:

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

int arr[] = {1, 2};

int **func(void)
{
    int **p;

    p = malloc(sizeof(int *) * 2);
    p[0] = &arr[0];
    p[1] = &arr[1];
    return p;
}

int main(void)
{
    int **p = func();

    printf("%d %d\n", *p[0], *p[1]);
    free(p);
    return 0;
}

关于c - 返回 main 时内存分配不是 "hold",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27058225/

相关文章:

c - 在c程序中添加0作为最后一个值

javascript - 删除数据后更新对象的对象

c++ - 以支持继承的方式在对象的构造函数中将 shared_ptr 添加到 self to vector

c++ - 在 C++ 中使用指针按引用传递数组

c - 在简单的 UNIX Shell 中实现历史记录的问题

c - STM32 SPI通信

c - 结构行为

c - 尝试将文本文件加载到数组中,出现段错误。有什么想法吗?

php - 将数组从 html 发布到 php

c - 为什么 `int *p = (char *) &num' 会导致警告?