對于一個專案,我必須在樹中插入節點。這棵樹很大,因為每個節點最多可以有 26 個子節點。為了做到這一點,我創建了一個結構如下:
typedef struct s_node
{
char letter;
struct s_node* f_letters[26];
word* flechies;
}t_node;
typedef struct s_tree
{
t_node* root;
}t_tree;
我也有這種結構來影響 .txt 檔案中的單詞:
typedef struct
{
char content[100];
char base_word[100];
int nature;
int genre;
int nombre;
int temps;
int personne;
}word;
letter 存盤一個字母, f_letters 存盤指向下一個字符的指標。這封信來自一個看起來像這樣的 .txt 檔案:
stabilimetre stabilimetre Nom:Mas SG
我正在嘗試將第一個單詞(此處為穩定性)中的字母放在節點中(每個節點一個字母)。我創建了兩個用于創建節點和顯示樹的函式:
t_node* new_value(char letter,t_tree *Tree, t_node* leaf)
{
t_node* n_node;
t_node n_node1;
n_node = &n_node1;
leaf->f_letters[0] = n_node;
n_node->letter = letter;
for (int i=0; i<26; i )
{
n_node->f_letters[i] = NULL;
}
return n_node;
}
void display_tree(t_tree t)
{
printf("The letter in this node is %c.\n",t.root->letter);
t_node* temp;
temp = t.root->f_letters[0];
printf("The letter in this node is %c.\n",temp->letter);
while(temp->f_letters[0] != NULL)
{
temp = temp->f_letters[0];
printf("The letter in this node is %c.\n",temp->letter);
}
}
這是我的主要內容:
int main () {
FILE *fp;
char str[5000];
char type[100];
t_tree Letter;
t_node* temp;
t_node temp1, first;
temp = &temp1;
Letter.root=NULL;
fp = fopen("dico_reducted.txt" , "r"); // Open the file in read mode "r"
if(fp == NULL) {
perror("Error opening file");
return(-1); // test if the file is not empty or if there is any issue
}
while (fgets (str, sizeof(str), fp)!=NULL) {
word A;
char word;
sscanf(str,"%s\t%s\t%s",&A.content, &A.base_word, &type); //Put every information from the text in the right spot
Letter.root = &first;
first.letter = 'N'; //This letter represent the type of the word (here noun)
first.f_letters[0] = temp;
temp->letter = A.content[0]; //The first 2 letters are putted manually and this is working
for (int i=1; i<12; i )
{
temp = new_value(A.content[i], &Letter, temp); // Here I put the following letters inside the tree
}
}
display_tree(Letter); //Here I'm trying to display the whole tree (It is working for only the first 2 letters
fclose(fp); // Close the file
return 0;
}
主要問題是我不知道哪個功能不起作用。我現在的輸出是:
The letter in this node is N. //This is good
The letter in this node is s. //This is good
The letter in this node is ▲. //Why is it displaying kind of an adress and why the program is stopping ?
我嘗試了很多事情,例如更改部分功能或通過一些 printf 手動顯示而不使用該功能,但發生了同樣的錯誤。我認為主要問題是 new_value 函式,但我不明白它是從哪里來的。最終輸出應該是:
The letter in this node is N.
The letter in this node is s.
The letter in this node is t.
The letter in this node is a.
The letter in this node is b.
The letter in this node is i.
The letter in this node is l.
The letter in this node is i.
The letter in this node is m.
The letter in this node is e.
The letter in this node is t.
The letter in this node is r.
The letter in this node is e.
uj5u.com熱心網友回復:
替換n_node = &n_node1;為n_node = malloc(sizeof(t_node));
解決我的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532312.html
標籤:C功能指针字符结构体
