2015-06-19 61 views
0

這裏我想用BST結構進行一些文本排序,所以我首先先做一些文本。但我再次遇到段錯誤。如此傷心:帶段錯誤的二叉搜索樹

#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 is some better way to initialize the first node 

int main() 
{ 
    //MyNode=malloc(sizeof(BSTnode)); /* initialize the first node*/ 
    MyNode->leftchild=NULL;    
    MyNode->rightchild=NULL; 
    strcpy(MyNode->data,"");  
    while(1) 
     prompt();     //always prompt the user for input 
            //and then use the function to store that 
            //input in that binary tree 

    return 0; 
} 

void prompt(){ 
    int i=0;  
    printf("Please select:\n"); 
    printf("1.input a data\n2.Exit\n"); 

    scanf("%d",&i); 
    switch(i){ 
     case 1: 
      inputData(); 
      break; 
     case 2: 
      exit(0); 
     default: 
      printf("Please input a valid number!(1 or 2)"); 
    } 
} 

void inputData(){ 
    char* data=""; 
    printf("Input your data here(character only/less than 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(" Your data have been input successfully!\n"); 
    return; 
} 

這就是所有的代碼。一旦我輸入一個單詞並按回車,我就會出現段錯誤。 我甚至不會嘗試打印數據。我現在想要做的是輸入一些數據並將其存儲在二叉搜索樹中。

但是,我沒有足夠的技巧......其實我還沒有取得成功的BST結構。所以如果你能幫助調試,我會非常感激。 cource,任何其他相關信息和代碼也將不勝感激。

回答

3

你在inputData中的數據指針指向一個常量(並且可能在堆中的某個地方初始化),你不應該那樣做。

您需要用malloc初始化內存,或者使用固定大小的數組f。恩。

void inputData(){ 
    char data[100]; 
    memset(data,0,sizeof(data)); 
    printf("Input your data here(character only/less than 19 characters!): "); 
    scanf("%s",data); 
    BSTnode** ptr=&MyNode; 
+0

+1,但如果您要立即寫入memset,則不需要memset。即使您需要初始化,您也可以簡單地執行:'char data [100] = {0};'。 –

+1

初始化數據的目的是爲了避免不結束字符串的問題,無論如何,scanf可能會繼續閱讀數組的長度,所以它可能毫無意義。 將scanf更改爲fgets,也許? (data,sizeof(data) - sizeof(char),stdin); data [sizeof(data)/ sizeof(char)-1] = 0; ' – IronDrake