C Linked List char数组输入重用问题

标签 c arrays input linked-list char

typedef struct NODE{
    char *word;
    struct NODE *next;
}node;

node *newNode(char *word) {
    node *pNode = (node*) malloc(sizeof(node));
    pNode->word = word;
    pNode->next = NULL;
    return pNode;
}

void append(node **ppList, char *word) {
    if(*ppList == NULL)
        *ppList = newNode(word);
    else {
        node *tmpList = *ppList;
        for(; tmpList->next!=NULL; tmpList=tmpList->next);
        tmpList->next = newNode(word);
    }
}

void printList(node *list) {
    for(; list!=NULL; list=list->next)
        printf("[%s]=>", list->word);
    printf("NULL");
}

/*=== CODE 1 ===*/
int main() {
    char word[MAXCHAR], word2[MAXCHAR], word3[MAXCHAR];
    node *list=NULL;

    scanf("%s", &word); /* key in AAA */
    append(&list, word);
    scanf("%s", &word2); /* key in BBB */
    append(&list, word2);
    scanf("%s", &word3); /* key in CCC */
    append(&list, word3);
    printList(list);
    return 0;
}

/*=== CODE 2 ===*/
int main() {
    char word[MAXCHAR];
    node *list=NULL;

    scanf("%s", &word); /* key in AAA */
    append(&list, word);
    scanf("%s", &word); /* key in BBB */
    append(&list, word);
    scanf("%s", &word); /* key in CCC */
    append(&list, word);
    printList(list);
    return 0;
}

输出:

=== CODE 1 OUTPUT ===
[AAA]=>[BBB]=>[CCC]=>NULL /* it works */

=== CODE 2 OUTPUT ===
[CCC]=>[CCC]=>[CCC]=>NULL /* doesnt work, why? */

嗨,我正在尝试循环这个东西然后我意识到它得到了错误的结果。我隔离了我的程序,我发现输入是问题所在,我尝试了 scanf,但两者都不起作用。为什么我不能用回 char 数组来存储输入,请有人帮我解决这个问题。

最佳答案

问题是您正在分配指针。

pNode->word = word;

因为 pNode->word 总是指向 main 中 word 的更新值。列表中的每个节点都将具有相同的值。

你应该在 main 中复制 word 的内容,而不是分配指针。

node *newNode(char *word) {
    node *pNode = (node*) malloc(sizeof(node));

    pNode->word = malloc(strlen(word)+1);
    strcpy(pNode->word, word);

    pNode->next = NULL;
    return pNode;
}

或者

node *newNode(char *word) {
    node *pNode = (node*) malloc(sizeof(node));

    pNode->word = strdup(word);

    pNode->next = NULL;
    return pNode;
}

注意:strdup 不是C 标准。

关于C Linked List char数组输入重用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53236665/

相关文章:

php - 为什么 laravel 中 get() 函数的返回值在检查 is_array 时不是数组

arrays - 从向量中排序的索引向量

ruby - 如何组合具有公共(public)元素的数组元素?

linux - Bash模拟终端gui程序的用户输入

字符和双指针声明

c - 字符到整数转换的巧妙之处

c++ - 通过 char C++ 检查 stringstream line char

javascript - 更改表单中所有输入的 DIV 背景颜色

c - 位编程

c++ - 如何在不更改其余代码的情况下替换 C++ 模板以使其与 C 兼容?