繁体   English   中英

如何在递归函数中将指针变量从被调用函数传递给调用函数?

[英]how to pass a pointer variable from the called function to the calling function in a recursion function?

在 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的节点。 (为了问题的清晰,我省略了二叉搜索树的创建)

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

#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);
}

查看ideone 上运行的代码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM