【问题标题】:C Linked List char array input reuse problemC Linked List char数组输入复用问题
【发布时间】:2019-04-13 16:03:19
【问题描述】:
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 数组来存储输入,有人可以帮我解决这个问题。

【问题讨论】:

  • 需要说明append函数是如何定义的,请提供minimal reproducible example
  • scanf("%s", &word); 而不是这个,试试这个:scanf("%s", word);
  • 投票关闭,因为不清楚你在问什么。请澄清您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。请参阅“如何提问”页面以获得澄清此问题的帮助。

标签: c arrays input linked-list char


【解决方案1】:

问题是你正在分配指针。

pNode->word = word;

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

您应该将word 的内容复制到main 中,而不是分配指针。

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

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 1970-01-01
    • 2014-05-21
    • 2021-03-25
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多