2010-03-22 79 views
1

我對C很陌生,我試圖在C中實現一個二叉樹,它將存儲一個數字和一個字符串,然後將它們打印出來,例如,描述只打印輸入的最後一個

1 : Bread 
2 : WashingUpLiquid 
etc. 

我到目前爲止的代碼是:

#include <stdio.h> 
#include <stdlib.h> 
#define LENGTH 300 

struct node { 
int data; 
char * definition; 
struct node *left; 
struct node *right; 
}; 

struct node *node_insert(struct node *p, int value, char * word); 

void print_preorder(struct node *p); 

int main(void) { 
    int i = 0; 
    int d = 0; 
    char def[LENGTH]; 
    struct node *root = NULL; 

    for(i = 0; i < 2; i++) 
    { 
    printf("Please enter a number: \n"); 
    scanf("%d", &d); 
    printf("Please enter a definition for this word:\n"); 
    scanf("%s", def); 
    root = node_insert(root, d, def); 
    printf("%s\n", def); 
    } 

    printf("preorder : "); 
    print_preorder(root); 
    printf("\n"); 

    return 0; 
} 

struct node *node_insert(struct node *p, int value, char * word) { 
    struct node *tmp_one = NULL; 
    struct node *tmp_two = NULL; 

    if(p == NULL) { 
    p = (struct node *)malloc(sizeof(struct node)); 
    p->data = value; 
    p->definition = word; 
    p->left = p->right = NULL; 
    } 
    else { 
    tmp_one = p; 
    while(tmp_one != NULL) { 
     tmp_two = tmp_one; 
     if(tmp_one->data > value) 
     tmp_one = tmp_one->left; 
     else 
     tmp_one = tmp_one->right; 
    } 

    if(tmp_two->data > value) { 
     tmp_two->left = (struct node *)malloc(sizeof(struct node)); 
     tmp_two = tmp_two->left; 
     tmp_two->data = value; 
     tmp_two->definition = word; 
     tmp_two->left = tmp_two->right = NULL; 
    } 
    else { 
     tmp_two->right = (struct node *)malloc(sizeof(struct node)); 
     tmp_two = tmp_two->right; 
     tmp_two->data = value; 
     tmp_two->definition = word; 
     tmp_two->left = tmp_two->right = NULL; 
    } 
    } 

    return(p); 
} 

void print_preorder(struct node *p) { 
    if(p != NULL) { 
    printf("%d : %s\n", p->data, p->definition); 
    print_preorder(p->left); 
    print_preorder(p->right); 
    } 
} 

目前它似乎爲int秒,但說明部分只打印出最後一個進入工作。我認爲它與char陣列上的指針有關,但我沒有運氣讓它工作。任何想法或建議?

回答

1

問題是您正在使用相同的字符串緩衝區。注意你的結構體持有一個指向char的指針,並且每次都傳遞與該指針相同的char數組。

當您在緩衝區上調用scanf時,您正在更改它指向的數據,而不是指針本身。

要解決此問題,在將其分配給結構之前,可以使用strdup。所以行代碼將成爲

tmp_*->definition = strdup(word); 

請記住,一旦你用它做的strdup通過返回的字符數組必須被釋放,否則你就會有一個泄漏。

+0

多數民衆贊成在它:)非常感謝傢伙,真的很煩我! – Paul 2010-03-23 00:45:18

+0

您現在應該點擊旁邊的綠色勾號選擇要接受的答案。這告訴系統該問題已得到解答,並且還給答覆者和你一些聲望。 – 2010-03-23 14:51:49

2

你總是在做一個def到scanf,然後將它傳遞給你的插入例程,它只保存指向def的指針。所以,因爲所有的條目都指向了def緩衝區,它們都指向你存儲在緩衝區中的最後一個字符串。

您需要複製您的字符串並將指向副本的指針放入二叉樹節點。