2013-04-01 26 views
0

'我需要能夠創建一個字母樹。然後用'.','-''/''//'打開一個示例.txt文件。 '.'在樹的左邊或在這種情況下是rist字母。「 - 」衝向右邊。 http://www.skaut.ee/?jutt=10201 - 樹看起來像什麼。 '用摩斯密碼讀取.txt文件,並從樹中查找字母?

#include <stdio.h> 
#include<stdlib.h> 
#include<string.h> 

struct MorsePuu { 
     char t2ht; 
     struct MorsePuu *punkt, *kriips, *next; 
}; 

static int i;  
char TAHED[32]={' ','E','I','S','H','V','U','F','Ü','A','R','L','Ä','W','P','J','T','N','D','B','X','K','C','Y','M','G','Z','Q','O','Ö','™'}; 
//creating the "alphabet-tree" 
struct MorsePuu *Ehitamine(int N) { 
    struct MorsePuu *uus; 
    int nl, nr; 
    if (N==0) {return NULL;} 
    else { 
     nl = N/2; 
     nr = N-nl-1; 
     uus = malloc(sizeof *uus); 
     uus->t2ht = TAHED[i]; 
     i++; 
     uus->punkt = NULL; 
     uus->kriips = NULL; 
     uus->punkt = Ehitamine(nl); 
     uus->kriips = Ehitamine(nr); 
     return uus; 
     } 
} 
//creating the order of the tree. 
    Preorder(struct MorsePuu *JViit) { 
    printf("%c",JViit->t2ht); 
    if (JViit->punkt != NULL) { 
     Preorder(JViit->punkt);} 
//  printf("%c",JViit->t2ht); Siin oleks Inorderi väljatrükk 
    if (JViit->kriips != NULL) { 
     Preorder(JViit->kriips);} 
//  printf("%c",JViit->t2ht); Ja siin oleks Postorderi väljatrükk 
} 



main(void) { 
    struct MorsePuu *morse, *abi;  
    char rida[128]; 
    FILE *fm=NULL; 

    printf("Käigepealt tuleb morsepuu ?les ehitada!"); 
    i = 0; 
    morse=Ehitamine(31); 
    printf("Puu väljatrükk preorder järjekorras.\n"); 
    Preorder(morse); 
    printf("%c",morse); 

    //opening the file . Contents e.g .-/.// return ie. // stops it. 
    fm = fopen("morse1.txt", "r"); 


    fgets(rida, 128, fm); 
    printf("\n %s", rida);  

    fclose(fm); 
    //this is where the reading and changing loop crashers. 
    /* 
    for(i=0; i<strlen(rida); i++){ 
     if(rida[i]=='/'){ 

     } 
     if(rida[i] == '.'){ 
      //printf(); 
      abi=abi->punkt;  
     } 
     if(rida[i]== '-'){ 
      abi=abi->kriips;   
     } 
     } 
    */ 
    } 

問題從最後一個循環開始。字母樹已創建,但我無法搜索樹中的字母。

回答

1

你沒有爲*abi分配任何內存這裏

main(void) { 
struct MorsePuu *morse, *abi;  
char rida[128]; 
FILE *fm=NULL; 

阿比是結構MorsePuu一個指針,它指向一個隨機位置,當你使用它後,你會在行abi=abi->punkt未定義行爲。

你必須添加一行

abi = malloc(sizeof(struct MorsePuu)) ;