我有以下结构:
typedef struct binTree_t {
int key;
enum {lMore, rMore, equal} ratio;
struct binTree_t* parent;
struct binTree_t* left;
struct binTree_t* right;
struct binTree_t** root;
} binTree_t;
它表示 AVL 树。问题似乎是根双指针。这个想法是,这种方式的更改*(node->root)
将传播到所有指向相同的节点node->root
。这种双重抽象应该确保**(node->root)
始终指向正确的根节点。但是,我为其分配内存的方式似乎存在问题:
binTree_t* createNode(int key, binTree_t* root) {
binTree_t* node = malloc(sizeof(binTree_t));
node->key = key;
node->ratio = equal;
node->parent =
node->left =
node->right = NULL;
node->root = root?&root:&node;
return node;
}
以下代码均正确返回12
:
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("%d", root->key); free(root);
return EXIT_SUCCESS;
}
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("%d", (*(root->root))->key); free(root);
return EXIT_SUCCESS;
}
但是,以下代码返回12
and 0
:
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("Text");
printf("%d", root->key); free(root);
return EXIT_SUCCESS;
}
int main(void) {
binTree_t* root = createNode(12, NULL);
printf("Text");
printf("%d", (*(root->root))->key); free(root);
return EXIT_SUCCESS;
}
看起来好像root->root
指针是在createNode
函数的堆栈上分配的?如果是这样,你建议我如何修复它,以便它使用分配的内存?