I'm having trouble with a binary tree algorithm. A test program I wrote calls for the top node to only be altered in another method outside main (A simple guessing/learning game scenario). I wrote a smaller test of that exercise here:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
struct binary {
unsigned long ID;
char *guess;
char isAns;
struct binary *yes;
struct binary *no;
};
typedef struct binary Node;
Node * make_question_answer(char *ques,char *ans);
Node * make_question_answer2(char *ques,char *ans);
void make_question_answer3(Node **change, char *ques,char *ans);
Node * getnew(char *msg, char isAns)
{
Node *nnew = malloc(sizeof(Node));
nnew->ID=clock();
nnew->guess=msg;
nnew->isAns=isAns;
nnew->yes=0;
nnew->no=0;
return nnew;
}
void dummy_method(Node **top)
{
char ques[128] = "ok";
char ans[128] = "ok";
printf("Node is null\n");
printf("Put in a question and answer to yes condition\n");
printf("Enter question: ");
while(!fgets(ques,128,stdin));
printf("Enter answer for yes condition: ");
while(!fgets(ans,128,stdin));
printf("Check ques: %s\nCheck ans: %s\n\n",ques,ans);
//(*top) = make_question_answer(ques,ans);
//(*top) = getnew(ques,'n');
make_question_answer3(top,ques,ans);
fprintf(stdout,"\ncheck in method: top: %s\n\n",(*top)->guess);
//(*top)->yes=getnew(ans,'y');
fprintf(stdout,"\ncheck in method: top->yes: %s\n\n",(*top)->yes->guess);
}
Node * make_question_answer(char *ques,char *ans)
{
Node *top = getnew(ques,'n');
top->yes = getnew(ans,'y');
return top;
}
Node * make_question_answer2(char *ques,char *ans)
{
Node *top = getnew(ques,'n');
Node *a = getnew(ans,'y');
top->yes=a;
return top;
}
void make_question_answer3(Node **change, char *ques,char *ans)
{
Node *top = getnew(ques,'n');
Node *a = getnew(ans,'y');
top->yes=a;
top->no=(*change);
*change=top;
}
int main()
{
Node *top=0;
dummy_method(&top);
/*char *ques = "sample question";
char *ans = "smaple answer";
top = make_question_answer(ques,ans);*/
fprintf(stdout,"\ncheck: %s\n\n",top->yes->guess);
}
The issue at hand is seen in the output:
Node is null
Put in a question and answer to yes condition
Enter question: test question
Enter answer for yes condition: test answer
Check ques: test question
Check ans: test answer
check in method: top: test question
check in method: top->yes: test answer
check: ?1?p?
From what I can tell all of those methods work in main, but not in dummy_method, which is confusing. Why might this be?