我对指向结构的指针的返回
值感到困惑。
我写了一个 AVL 树
。这是我的头文件片段-
typedef struct AVLNode {
struct AVLNode *left,
*right;
int value,
height;
} AVLNode;
typedef struct AVLNode *AVLTree;
AVLNode *delet(int value, AVLTree t);
这是我的 delet()
和 main()
-
AVLNode *delet(int value, AVLTree t)
{
if (t == NULL) {
printf("Node not found\n");
return t;
}
else if (value == t->value) {
.....
return t;
}
else if (value < t->value) {
if (t->left != NULL) {
t->left = delet(value, t->left);
}
if (height(t->left) - height(t->right) == 2) {
if (t->value < t->left->value)
t = rotateR(t);
else
t = rotateLR(t);
}
.....
return t;
}
else if (value > t->value) {
if (t->right != NULL) {
t->right = delet(value, t->right);
}
.....
return t;
}
}
void main()
{
AVLTree t = NULL;
.....
t = delet(4, t); /* works fine */
delet(4, t); /* gives improper results */
.....
}
在这里,我返回 t
(属于 AVLNode *
类型)。虽然我意识到这在递归 delet()
调用中是必不可少的
,但我不明白的是 -
- 当我从
main()
调用t = delet(4, t)
时,它会给我正确的结果,而只调用delet(4, t )
给出了错误的结果。 - 如果我在
delet(t)
中传递一个指针(t
是一个AVLNode *
),为什么我需要收集它再次在指针中?
最佳答案
这是因为您已经“按值”传递了 AVLTree t
。将t
的地址传给delet
,然后修改。
现在你只修改你在delet
函数中声明的AVLTree t
的本地副本:
AVLNode *delet(int value, AVLTree t)
尝试将函数声明为 AVLNode *delet(int value, AVLTree *p_t)
,调用将是 delet(4, &t);
。
编辑:(在 OP 的评论中)
当你需要在一个函数中修改一个值时:
void swap(int a, int b)
{
int t;
t = a;
a = b;
b = t;
}
这不起作用,因为您需要修改 a
和 b
,它们的“副本”是您传递给函数的。
与您的情况类似,您需要修改指针 AVLTree t
所持有的地址,即指针本身,因此需要在此处传递“指针的地址”而不是所持有地址的副本指针。
关于c - 返回指向 C 中结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21745366/