【问题标题】:linked list of type void*void* 类型的链表
【发布时间】:2011-02-01 17:11:38
【问题描述】:

我正在尝试读取文本文件并将每一行存储在 void* 类型的链接列表的节点中。 这是列表的头文件。

#ifndef LINKEDL
#define LINKEDL

struct node_s {
    void *data;
    struct node_s *next;    
};

struct node_s *node_create(void*);
struct node_s *list_insert_after(struct node_s*, void*);
struct node_s *list_insert_beginning(struct node_s*, void*);
int list_remove(struct node_s*, struct node_s*);
int list_foreach(struct node_s*, int(*)(void*));
int printstring(void *s);


#endif

所有的链表函数都经过了彻底的测试,所以我想问题在于我如何使用它。我想要实现的是每个节点都有一行,而我现在拥有的是每个节点的最后一行。我想这与 char 指针有关,但已经花了两个小时没有取得惊人的突破,所以也许有人可以帮忙? 此外,我使用的列表是修改后的列表,如 here 所示。

 if (file == NULL)
 {
    perror("Error opening file");
 }
 else 
 {
     char mystring[SIZE];
     char temp[SIZE];

     list = node_create((void*)mystring);
     current = list;
     while (fgets(mystring, SIZE, file) != NULL)
        {
            strcpy(temp, mystring); 
            printf("%d\t%s",counter++,temp);
            current=list_insert_after(current, (void*)temp);                    
            }
            fclose(file);

        }

更新: 谢谢大家。

【问题讨论】:

  • 你只有一个字符串变量(mystring),所以你所有的节点都指向同一个字符串。您需要为要指向的每个新节点分配一个新字符串。

标签: c gcc linked-list


【解决方案1】:

您正在使用单个数组 temp 创建每个节点。每次阅读一行时,都将 temp 的内容替换为您阅读的最后一行。这就是为什么您在每个节点上都有最后一行(您指的是每个节点中的相同内存位置)。

您应该做的是使用 malloc 为每一行动态分配内存。因此,您应该将指向新分配内存的指针传递给 list_insert_after 而不是传递 temp。

【讨论】:

    【解决方案2】:

    删除线:

    strcpy(temp, mystring); 
    

    然后换行:

    current=list_insert_after(current, (void*)temp);
    

    current=list_insert_after(current, strdup(mystring));
    

    【讨论】:

    • 如果能看到free 用法的例子也很好。
    • 没有可修复的代码遍历列表并销毁它。
    【解决方案3】:

    考虑一下 - 您在堆栈上有一个临时 char 数组,该数组在退出范围(else 块)时被销毁,并且您正在将该数组的指针插入到列表中。所以毕竟,列表最终会有指向被破坏/不正确数据的指针。行为未定义。

    您必须为每个字符串动态分配内存(并且不要忘记清理它)。 strdup 在这里很有用。从该列表中删除/删除字符串时不要忘记调用free

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      相关资源
      最近更新 更多