C链表char数组输入重用问题

时间:2018-11-10 06:47:56

标签: 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数组来存储输入,有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

问题是您正在分配指针。

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的标准。