in C the called function cannot directly alter a variable in the calling function, it can only alter its private, temporary copy. so I use the pointer variable to alter and to pass the variable in the called function to the calling function. But in a recursion function, the function calls itself. In the first recursion, I use a pointer, and in the second recursion, the function asks for a pointer that points to the prior pointer. And in the next recursion, a pointer that points to the pointer in the second recursion is asked. How to avoid this condition since my aim is to pass the variable that is created in the called recursion function?
given the data of a node, I want to search and alter the node in a binary search tree. I use the pointer variable aPointerToNode
to locate the node, but when I use the recursive functionSearchBST
, I pass a pointer that points to aPointerToNode
so that I can alter it in the called function. But when the recursive function calls itself, the function asks for another pointer that points to the prior pointer. If I give the function the prior pointer but not another pointer that points to the prior pointer, the function will not return the node that I search for, that is, it just creates a temporary copy and returns nothing(I want to use the arguments but not the return value of the function to pass the variable).
#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);
}
finally, in the function main()
, the variable aPointerToNode
points to the node that has the targetInfo
. (I omit the creation of the binary search tree for the clearness of the question)