2017-03-01 69 views
-3

以下是我正在使用的三种结构,例如当我的程序 将'the'作为第一个单词时,它使* rt-> str = the。 但是,当读取下一个单词时,该键等于* rt-> str,我不明白为什么。我是一名C程序员初学者,这确实阻碍了我的发展。为什么根改变其数据?

struct node { 
    char *str; 
    int occ; 
    struct node *sibling; 
    struct node *child; 
}; 

struct node* root; 

struct node* getNew(char word[100]) { 
    struct node *newNode; 
    newNode = (struct node *)malloc(sizeof(struct node)); 
    newNode->str = word; 
    newNode->sibling = NULL; 
    newNode->child = NULL; 
    newNode->occ = 0; 
    return newNode; 
} 

struct node* insert(char key[100], struct node **rt){ 

    if(*rt == NULL) { 
     *rt = getNew(key); 
     printf("This is the key in the root: %s\n", (*rt)->str); 
     return *rt; 
    }else{ 
     printf("root word: %s\n", (*rt)->str); 
     exit(0); 
    } 

    struct node *leaf = *rt; 
    int n = 0; 
    int i; 
    char w2[100]; 
    strcpy(w2, key); 

    printf("root word: %s\n", (*rt)->str); 

    for(i = 0; i < strlen((leaf)->str); i++) { 
     printf("%c %c \n", (leaf)->str[i], key[i]); 
     if((key[0] == (leaf)->str[i])) { 
      n++; 
      key = key + 1; 
      printf("key is: %s \n", key); 
     } 
    } 

    if(key[0] == 0) { 
     printf("key is empty \n"); 
    } 

    printf("This is the word after for loop: %s \n", key); 
    exit(0); 
} 
+4

'if(...)return ..; else exit();'使得该函数的其余部分无法访问。 – mch

+2

学习使用调试器。每当你的代码不能做你想要的东西时,你都不会问得太远。 – rustyx

+0

也在'getNew','newNode-> str = word;'你可能想在这里使用['strdup'](http://en.cppreference.com/w/c/experimental/dynamic/strdup)。 –

回答

1

此:

newNode->str = word; 

不复制字符串(如,是建立在字符串中的字符),它只是拷贝一个字符串,它是一个参数的位置。当该函数退出时,该位置将不会保持有效,因此,稍后访问时会导致未定义的行为。

C不支持分配数组,而数组也不是指针。

相关问题