I want create this BinTree .
in this function it can't work.
typedef struct BinNode {
Elemtype data;
struct BinNode* left;
struct BinNode* right;
}BinNode,*BinTree;
void createBinTree(BinTree* root, char* a) {
if (*a == '\0')
return;
if (*a == '#') {
(*root) = NULL;
return;
}
else {
(*root) = (BinTree)malloc(sizeof(BinNode));
assert((*root) != NULL);
(*root)->data = *a;
createBinTree(&(*root)->left, ++a);
createBinTree(&(*root)->right, ++a);
return;
}
}
int main() {
char* ptr = "ABC##DE##F##G#H##";
BinTree my_tree = NULL;
createBinTree(&my_tree,ptr);
return 0;
}
I try to run this function,It doesn't create the correct BinTree like in the picture。 but this way can.
void createBinTree(BinTree* root, char** a) {
if (**a == '\0')
return;
if (**a == '#') {
(*root) = NULL;
(*a)++;
return;
}
else {
(*root) = (BinTree)malloc(sizeof(BinNode));
assert((*root) != NULL);
(*root)->data = **a;
(*a)++;
createBinTree(&(*root)->left, a);
createBinTree(&(*root)->right, a);
return;
}
}
int main() {
char* ptr = "ABC##DE##F##G#H##";
BinTree my_tree = NULL;
createBinTree(&my_tree,&ptr);
return 0;
}
why it can. i don't understand why call createBinTree need pass &ptr but **ptr.**please help me!
In the first program the value of the pointer
ain the second call of the functionis not equal to the last value of the pointer
aafter the first call of the functionConsider for example the initial processing of the string.
In the first call of the function there is passed the pointer
athat points to the character'B'.In the second call of the function there is passed the pointer
athat points to the character'C'instead of pointing to the character'#'.In the second program the pointer
ais passed by reference through a pointer to it. So after the first call of the function the value of the pointerawill be the last value of the pointer after the first function call.