免费的双指针结构

时间:2018-11-19 04:09:38

标签: c arrays struct malloc free

我想将所有MinHeapNode放入一个数组中,并在程序完成打印后将它们释放。

以下是创建数组并释放它的代码:

void HuffmanCodes(int data[], int freq[], int size) {
        struct MinHeap *clear;
        int s = 0;
        struct MinHeapNode *nodes = malloc(sizeof(struct MinHeapNode) * ((4 * 2) - 1));
        struct MinHeapNode *root = buildHuffmanTree(data, freq, size, &clear);
        int arr[MAX_TREE_HT], top = 0;
        printCodes(root, arr, top, &nodes, &s);
        int i;
        for (i = 0; i < s; i++) {
                free(nodes[i]);
        }
        free(nodes);
        free(clear->array);
        free(clear);
}

这里是获取每个MinHeapNode并将其放入节点的代码

void printCodes(struct MinHeapNode *root, int arr[], int top, struct MinHeapNode **nodes, int *s) {
        if (root->left) {
                arr[top] = 0;
                printCodes(root->left, arr, top + 1, nodes, s);
        }
        if (root->right) {
                arr[top] = 1;
                printCodes(root->right, arr, top + 1, nodes, s);
        }
        if (isLeaf(root)) {
                printf("%d: ", root->data);
                printArr(arr, top);
        }
        nodes[*s] = root;
        *s++;
}

printCodes 的最后两行替换为“ free(root);”。可以,但是我想在功能之外释放它。

0 个答案:

没有答案