【问题标题】:Correct AddNode function but somehing happens when I printf正确的 AddNode 函数,但是当我 printf 时发生了一些事情
【发布时间】:2014-12-31 13:42:31
【问题描述】:

我已经用不同的列表测试了 addNode 函数和 printf 循环,它们工作正常。但是这个有问题,因为当我打印列表时它会打印头部,然后所有其他单词都与用户给出的最后一个单词相同。

这是addnode(这个词是用户给出的-我检查过,它工作正常)

struct list* addNode(struct list* head, char *word){

struct list *curr,*help,*Nhead;

curr=(struct list *)malloc(sizeof(struct list));

curr->sorted=head->sorted;          
if(curr->sorted==false){    
    Nhead=head;
    while(head->next!=NULL){
        head=head->next;
    }
    curr->data.word=word;
    curr->prev=head;
    curr->next=NULL;
    head->next=curr;

}
else{
    Nhead=head;
    for(help=head; help!=NULL; help=help->next){        
        if(strcmp(word,help->data.word)<0){             
            break;
        }
    }   
    if(help==NULL){ 
        for(help=head; help->next!=NULL; help=help->next){}
        curr->next=NULL;
        curr->data.word=word;
        curr->prev=help;
        help->next=curr;
    }
    else{
        curr->next=help;
        curr->prev=help->prev;
        curr->data.word=word;
        help->prev=curr;
        if(help!=head){
            help=curr->prev;
            help->next=curr;
        }
        else{
            Nhead=curr;
        }
    }

}   


    return Nhead;
}

这就是我的打印方式

for(curr=pathWordsH; curr!=NULL; curr=curr->next){
        printf("%s",curr->data.word);
        if(curr->next!=NULL){
            printf("-->");
        }
    }

【问题讨论】:

    标签: c list printing add


    【解决方案1】:

    你没有在文字中展示你是如何阅读的,但我想这就是发生的事情:

    当您从用户那里获取输入时,您可能会使用相同的字符缓冲区。您将该字符缓冲区分配给列表节点的word,并在您构建列表时保存当前单词。完成后,所有节点都引用同一个字符缓冲区,其内容是用户提供的最后一个单词。

    因此,您应该复制内容而不是分配指针。基本上有两种方法:为每个节点分配内存给list-&gt;word,或者使word条目成为固定大小的缓冲区。

    (非标准,但广泛使用)函数strdup 在堆上复制一个字符串。所以不要分配指针

    curr->data.word = word;
    

    分配内容的副本:

    curr->data.word = strdup(word);
    

    因为你已经分配了额外的内存,你应该在销毁一个列表节点时释放word中的内存。

    【讨论】:

    • printf("\n输入选择:\n"); scanf("%s", cur_word);这就是我在 while 循环中读取单词的方式。但我没有完全抓住你。我只需要更改您提供的代码吗?
    • 然后是head = addNode(head, cur_word),对吗?您的所有列表节点都将具有list-&gt;word == cur_word,因此您最终会为所有节点打印相同的值。您的cur_word 是暂存空间,您必须复制内容。一种方法是使用strdup。你试过了吗?
    • 作为一个反例,如果您不要求用户在循环中输入而是执行以下操作:head = addNode(head, "Apple"); head = addNode(head, "Banana"); head = addNode(head, "Cherry") 然后打印列表,它应该可以工作。这是因为字符串文字(双引号)都存储在不同的内存地址。在 C 中使用指针的部分困难在于知道何时可以指向现有内存以及何时必须复制内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2011-09-16
    相关资源
    最近更新 更多