c - 链表给出相同的结果 C

标签 c linked-list

在该方法的最后,我所有的测试 printfs 都打印出相同的结果。文件的最后一行。但是 while 循环中的当前 printf 工作正常。出于某种原因,我的节点具有相同的结果。我该如何解决? 这是我的结构单元:

struct unit
{
    struct unit * next;
    char *name;
};

这是我的链表函数,一条一条地向链表添加行:

void readFile(char fileName[], struct unit * units)
{
    FILE * fp;
    char *line = NULL;
    int length = 1000;
    fp = fopen(fileName, "r");
    int counter = 0;
    int strLength = 0;
    struct unit * current;

    units = (struct units*)malloc(sizeof(struct unit));
    current = units;

    while ( getline(&line, &length, fp) != -1)
    {
        strLength = strlen(&line);
        current->name = (char*)malloc(sizeof(char)* strLength);
        current->next = (struct units*)malloc (sizeof(struct unit));
        strcpy(&current->name, &line);
        printf("\nCurrent: %s",current->name);
        current  = current->next;
        counter++;
    }
    printf("\nTest %s", units->name);
    printf("\nTest %s", units->next->name);
    printf("\nTest %s", units->next->next->name);
    printf("\nTest %s", units->next->next->next->name);
}

最佳答案

为什么要将 &line 传递给 strlenstrcpy?如果我没记错的话,你应该将 linecurrent->name 传入这些函数。 (虽然我不知道 getline;也许这样没问题。)

关于c - 链表给出相同的结果 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21767821/

相关文章:

c - Node->next!=NULL 和 Node!=NULL 在 C 中的区别

c - 此 "good taste"和 "bad taste"代码中是否缺少 free()?

以太网传输时字节顺序的变化

c - C 中的位域,其结构包含结构的并集

c - C 中的字符串和 ASCII 字符串有区别吗?

java - 如何在Java中添加到链表的开头

c - 与程序堆栈执行相关的链表程序流程

java - Eclipse 在 Debug模式下挂起我的进程

c - 从文件读取字符串时出错

比较 C 中的字符会引发错误