c - 为什么我的链接列表只打印最后一个条目?

标签 c file linked-list

我正在尝试从文件中读取特定行并将其添加到链接列表中,然后将其打印出来。
代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 typedef struct list {
    int uid;
   char* uname;
   struct list* next;
}node;



void push(node ** head, int uid ,char* uname) {
    node * new_node;
    new_node = malloc(sizeof(node));
    new_node->uid = uid ;
    new_node->uname=uname;;
    new_node->next = *head;
    *head = new_node;
}


void print_list(node *head) {
    node * current = head;
    while (current != NULL) {
        printf("%u:%s\n", current->uid,current->uname);
        current = current->next;
    }
}


int main(int argc, char **argv){

    node *current=NULL;
    FILE *fp=fopen(argv[1],"r" );
    if (fp==NULL){
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }
    char s[1024];
    const char token[2]=":";
    char *stoken;
    while(!feof(fp)){
        int count=0;
        int tempint;
        char* tempchar=malloc(sizeof(char));
        fgets(s, 1024, fp);
        stoken = strtok(s,token);
        current=malloc(sizeof(node));
        while(stoken != NULL){
            if (count==0){
                tempchar=stoken;
            }
            if (count==2){
                sscanf(stoken,"%d",&tempint);
            }
            count++;
        stoken=strtok(NULL,token);
        }
        push(&current,tempint,tempchar);
    }
    fclose(fp);
    print_list(current);
}

我的问题是,当 print_list 运行时,唯一打印的内容是最后一个条目。

对于此输入:

hello:asd:123:foo:ar

hi:proto:124:oo:br

hey:qwe:321:fo:bar

唯一打印的是

321:hey

是我的push错误还是我的print_list错误?

最佳答案

问题在于您处理 strtok 结果的方式:您将其值直接设置到节点中,而不是复制它。

添加节点时复制name:

void push(node ** head, int uid ,char* uname) {
    node * new_node;
    new_node = malloc(sizeof(node));
    new_node->uid = uid;
    new_node->uname=malloc(strlen(uname)+1);
    strcpy(new_node->uname, uname);
    new_node->next = *head;
    *head = new_node;
}

您还应该查看在 main 函数中使用 tempchar 的方式。您为单个字符分配了一个空间,该空间会被 strtok 的结果覆盖,从而泄漏 malloc 编辑的内存。

关于c - 为什么我的链接列表只打印最后一个条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30881177/

相关文章:

java - Java中反转链表的程序

c - sigset_t、time_t的_t后缀的含义

c - 使用递归打印所有排列

c - 如何从 json 字符串中获取值?

java - 为什么我无法将数据存储在 .txt 文件中?

c++ - 返回组件时链表段错误

java - 从LinkedList的实现继承到SortedLinkedList,访问私有(private)Node

java - jni-wrapper-to-openssl-AES_encrypt-不工作

python - 如何在 python 中打开文件并向其中插入一个或多个输入?

Java - 解释对象文件