【问题标题】:how to pass a pointer variable from the called function to the calling function in a recursion function?如何将指针变量从被调用函数传递给递归函数中的调用函数?
【发布时间】:2019-12-06 20:28:58
【问题描述】:

在 C 中,被调用函数不能直接更改调用函数中的变量,它只能更改其私有的临时副本。所以我使用指针变量来改变并将被调用函数中的变量传递给调用函数。但在递归函数中,函数调用自身。在第一次递归中,我使用了一个指针,而在第二次递归中,函数要求一个指向前一个指针的指针。并且在下一次递归中,会询问一个指向第二次递归中指针的指针。由于我的目标是传递在调用的递归函数中创建的变量,如何避免这种情况?

给定一个节点的数据,我想在二叉搜索树中搜索和更改节点。我使用指针变量aPointerToNode 来定位节点,但是当我使用递归函数SearchBST 时,我传递了一个指向aPointerToNode 的指针,以便我可以在被调用函数中更改它。但是当递归函数调用自身时,函数会请求另一个指向前一个指针的指针。如果我给函数一个先验指针而不是另一个指向先验指针的指针,该函数将不会返回我搜索的节点,也就是说,它只是创建一个临时副本并且什么都不返回(我想使用参数但不是传递变量的函数的返回值)。

#include<stdio.h>

struct t_Data
{
  int m_Info;
};

struct t_Node
{
  struct t_Data m_Data;
  struct t_Node* m_LeftChild;
  struct t_Node* m_RigthChild;
};

typedef struct t_Node* t_BinarySortTree;

void SearchBST(t_BinarySortTree T,int aGivenInfo, struct t_Node* *result)
{
  if(aGivenInfo == (*T).m_Data.m_Info)
  {
    (*result) = T;
  }
  else if (aGivenInfo < (*T).m_Data.m_Info)
  {
    SearchBST((*T).m_LeftChild,aGivenInfo,result);
  }

  /* condition: aGivenInfo > (*T).m_Data.m_Info */
  else
  {
    SearchBST((*T).m_RightChild,aGivenInfo,result);
  }
}

void main(void)
{
  t_BinarySortTree aBST;
  aBST = NULL;

  int targetInfo;
  targetInfo = 58;

  struct t_Node* aPointerToTargetNode;
  aPointerToTargetNode = NULL;


  SearchBST(aBST,targetInfo,&aPointerToTargetNode); 
}

最后,在函数main() 中,变量aPointerToNode 指向具有targetInfo 的节点。 (为了问题的清晰,我省略了二叉搜索树的创建)

【问题讨论】:

  • 为了更好的可读性,(*T). 等同于T-&gt;
  • (*result) == T;?那不会有太大作用。启用更详细的警告,编译器会为您捕捉到它。
  • 避免为指针创建 typedef。 stackoverflow.com/questions/750178/…
  • 传递指针是可以的。在递归函数中,我只需要传递指针变量本身作为下面第一个答案中的示例。我将(*result) = =T 替换为(*result = T),因此指针的更改不起作用。即使我看到上面的评论,我仍然认为它是正确的。

标签: c pointers recursion data-structures binary-search-tree


【解决方案1】:

您不需要指向指针的指针...指向指针的指针。基指针不变

#include <stdio.h>
void rec(int *p, int n) {
    if (n == 0) return;
    *p += n;
    rec(p, n - 1);
}
int main(void) {
    int sum = 0;
    rec(&sum, 100);
    printf("sum is %d\n", sum);
}

code running on ideone

【讨论】:

    【解决方案2】:

    与其在递归函数中传递变量,不如让它成为全局变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 2018-07-29
      • 2017-03-25
      • 2017-10-13
      • 2010-10-02
      • 2012-04-15
      • 2016-10-23
      • 1970-01-01
      相关资源
      最近更新 更多