返回指向C中结构的指针

时间:2014-02-13 04:37:00

标签: c pointers data-structures struct

我对指向结构的指针return值感到困惑 我写了AVL Tree。这是我的标题文件摘要 -

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()电话中意识到这是必不可少的,但我不明白的是 -

  • 当我从t = delet(4, t)拨打main()时,它会给我正确的结果,而只是调用delet(4, t)会给出错误的结果。
  • 如果我在delet(t)传递指针(tAVLNode *),为什么我需要再次在指针中收集它?

2 个答案:

答案 0 :(得分:1)

这是因为您已通过值“AVLTree t”。将t的地址传递给delet,然后进行修改。

现在您只修改在AVLTree t函数中声明的delet的本地副本:
AVLNode *delet(int value, AVLTree t)

尝试将该功能声明为AVLNode *delet(int value, AVLTree *p_t),并且呼叫将为delet(4, &t);

编辑:(AT OP的评论)

当您需要修改函数内的值时:

void swap(int a, int b)
{
  int t;
  t = a;
  a = b;
  b = t;
}

这不起作用,因为您需要修改ab,其“副本”是您的功能。

同样在你的情况下,你需要修改指针AVLTree t所持有的地址,即指针本身,因此“指针的地址”需要在这里传递,而不是指针所拥有的地址副本。

答案 1 :(得分:1)

你需要这个

 AVLNode *delet(int value, AVLTree* t)

AVLTree t;
 delet(4,&t);
相关问题