C: Why can't I change the top binary tree node in a non-main method? -
i think more of pointer problem binary tree problem. exercise re-creating guessing/learning game in c using binary tree. had method, traverse, go through tree , ask questions, etc. method, when found non-existent node ask user input create node, hence learning part. when corrupted data. recreation of relevant code:
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 traverse(node **top) { char ques[128] = "ok"; char ans[128] = "ok"; printf("node null\n"); printf("put in question , answer yes condition\n"); printf("enter question: "); while(!fgets(ques,128,stdin)); printf("enter answer yes condition: "); while(!fgets(ans,128,stdin)); printf("check ques: %s\ncheck ans: %s\n\n",ques,ans); make_question_answer(top,ques,ans); fprintf(stdout,"\ncheck in method: top: %s\n\n",(*top)->guess); fprintf(stdout,"\ncheck in method: top->yes: %s\n\n",(*top)->yes->guess); } void make_question_answer(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; traverse(&top); fprintf(stdout,"\ncheck: %s\n\n",top->yes->guess); }
using make_question_answer() in main change top, , works in traverse won't last in jump main. points corrupted data seen fprintf. have no idea why happening.
in getnew() you're assigning nnew->guess stack variable. consider allocating memory string , using strncpy() or other mechanism fill in newly allocated memory.
Comments
Post a Comment