我编写了一个函数,将指向对象的指针追加到数组中,但是当从嵌套函数调用它时,
realloc
无法正确重新分配内存。然而,当我从函数重新分配内存时,之前已经分配了对象,一切都很好
这是我的代码的简化示例:
#include <stdlib.h>
typedef struct Node
{
char ch;
int freq;
struct Node *left, *right;
} Node;
Node *newNode(char ch, int freq, Node *left, Node *right)
{
Node *node = (Node *)malloc(sizeof(Node));
node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;
return node;
};
void pushNode(Node **nodes, Node *node, int *nodesCount)
{
nodes = (Node **)realloc(nodes, ++(*nodesCount) * sizeof(Node *)); // error
nodes[*nodesCount - 1] = node;
}
int main()
{
int nodesCount = 0;
Node **nodes = (Node **)calloc(0, sizeof(Node *));
Node *node = newNode('\0', 0, NULL, NULL);
// pushNode(nodes, node, &nodesCount);
nodes = (Node **)realloc(nodes, ++nodesCount * sizeof(Node *)); // no error
nodes[nodesCount - 1] = node;
return 0;
}
您的错误来自
nodes
,它是pushNode
函数的本地函数,您应该有类似的内容:
void pushNode(Node ***nodes, Node *node, int *nodesCount)
{
Node **newNodes;
newNodes = (Node **)realloc(*nodes, ++(*nodesCount) * sizeof(Node *));
/* check newNodes */
*nodes = newNodes
(*nodes)[*nodesCount - 1] = node;
}