簡體   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