【问题标题】:Why does the root change its data? [closed]为什么根会更改其数据? [关闭]
【发布时间】:2017-03-01 12:59:29
【问题描述】:

这是我正在使用的三个结构,例如当我的程序 将 '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);
}

【问题讨论】:

  • if (...) return ..; else exit(); 使函数的其余部分无法访问。
  • 学习使用调试器。每次你的代码没有达到你想要的效果时,你都不会走得太远。
  • 同样在getNew, newNode-&gt;str = word; 你可能想在这里使用strdup

标签: c trie


【解决方案1】:

这个:

newNode->str = word;

不复制字符串(如构成字符串的字符),它只是复制 a 字符串的位置,这是一个参数。当函数退出时,该位置将不再有效,因此当您稍后访问它时,这会给您带来未定义的行为。

C不支持赋值数组,数组不是指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    相关资源
    最近更新 更多