c - 返回指向 C 中结构的指针

标签 c pointers data-structures struct

我对指向结构的指针返回值感到困惑。
我写了一个 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;
}

这不起作用,因为您需要修改 ab,它们的“副本”是您传递给函数的。

与您的情况类似,您需要修改指针 AVLTree t 所持有的地址,即指针本身,因此需要在此处传递“指针的地址”而不是所持有地址的副本指针。

关于c - 返回指向 C 中结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21745366/

相关文章:

c++ - 如何使用外部库中的函数?

c - getcontext 和 savecontext 在优化下表现不同

algorithm - 有没有办法减少这个队列的内存使用?

c++ - 我的类(指向另一个类的指针的容器)似乎无法访问公共(public)构造函数

mysql - 存储数据库结构

c - 错误 :Segmentation fault(code dump)

c - 解决 “Writing Secure Code” 中的安全漏洞 '

c - 奇怪的 C 语法 1 ["ABCDE"]?

c - 无法预测以下程序的输出

c++ - 我能保证所有指针都具有相同的字节大小吗?