c - A binary search tree with segfault -
here want make text sorting bst structure, first text first. segfault again. sad it:
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct bstnode{ struct bstnode* leftchild; struct bstnode* rightchild; char data[20]; }bstnode; void prompt(); void inputdata(); bstnode firstnode; bstnode* mynode=&firstnode; //maybe there better way initialize first node int main() { //mynode=malloc(sizeof(bstnode)); /* initialize first node*/ mynode->leftchild=null; mynode->rightchild=null; strcpy(mynode->data,""); while(1) prompt(); //always prompt user input //and use function store //input in binary tree return 0; } void prompt(){ int i=0; printf("please select:\n"); printf("1.input data\n2.exit\n"); scanf("%d",&i); switch(i){ case 1: inputdata(); break; case 2: exit(0); default: printf("please input valid number!(1 or 2)"); } } void inputdata(){ char* data=""; printf("input data here(character / less 19 characters!): "); scanf("%s",data); bstnode** ptr=&mynode; while(1){ if(strcmp(data,(*ptr)->data)){ if((*ptr)->rightchild!=null){ ptr=&((*ptr)->rightchild); continue; } else{ (*ptr)->rightchild=malloc(sizeof(bstnode)); ptr=&((*ptr)->rightchild); (*ptr)->rightchild=null; (*ptr)->leftchild=null; strcpy((*ptr)->data,data); break; } } else{ if((*ptr)->leftchild!=null){ ptr=&((*ptr)->leftchild); continue; } else{ (*ptr)->leftchild=malloc(sizeof(bstnode)); ptr=&((*ptr)->leftchild); (*ptr)->leftchild=null; (*ptr)->rightchild=null; strcpy((*ptr)->data,data); break; } } } printf(" data have been input successfully!\n"); return; }
that code. , segfault once input word , press return. don't try print data out. want input data , store in binary search tree.
but, not skillful enough... haven't make successful bst structure. appreciate if can debug. of cource, other related information , code appreciated.
your data pointer in inputdata pointing constant (and maybe initialized somewhere in heap), shouldn't that.
you need initialize memory malloc or, use fixed-size array, f. ex.
void inputdata(){ char data[100]; memset(data,0,sizeof(data)); printf("input data here(character / less 19 characters!): "); scanf("%s",data); bstnode** ptr=&mynode;
Comments
Post a Comment