' 我需要能够创建一个字母树。然后使用 '.'
、'-'
和 '/'
'//'
打开示例 .txt 文件>。 '.'
转到树的左侧,或者在本例中为 rist 字母。'-'dash 到右侧。
http://www.skaut.ee/?jutt=10201 - 这棵树是什么样子的。 '
#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;
}
}
*/
}
问题是从最后一个循环开始的。字母树已创建,但我无法从树中搜索字母。
最佳答案
您没有在这里为 *abi
分配任何内存
main(void) {
struct MorsePuu *morse, *abi;
char rida[128];
FILE *fm=NULL;
Abi 是一个指向 struct MorsePuu 的指针,它指向一个随机位置,当您稍后使用它时,您会在 abi=abi->punkt
行导致未定义的行为。
您必须添加一行
abi = malloc( sizeof( struct MorsePuu )) ;
关于c - 使用摩尔斯电码读取 .txt 文件并从树中查找字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747407/