c - 在链表中存储行 (c)

标签 c data-structures linked-list

我认为我在链表的工作方式上遇到了一些问题,请记住我不是 C 语言专家并且我之前没有使用过链表。

我正在尝试获取包含事物列表的文本文件并将其存储在链表中。我现在有以下代码:

typedef struct linked_list {
    struct linked_list *next_ptr;
    char name;
    float price1;
    float price2;
}linked_list;

struct linked_list *first_ptr;
char name_temp;

int writeList(void) {
    // read input files
    FILE *sh_list;
    sh_list=fopen("case1/shoppingList.dat", "rw");
    if (sh_list == NULL) {
        perror("Cannot open file, you seem to have something mixed up...");
        exit(8);
    }

    struct linked_list *current_ptr;
    current_ptr = first_ptr;

    while ((fscanf(sh_list, "%s", &name_temp)) !=EOF) {
        next_ptr = malloc(sizeof(linked_list));
        strcpy(name, name_temp);
        //move to next node and complete the same task
    }
};

我在//move... 处停了下来,因为我正在努力让代码正确 - 我的 IDE 给我错误。同样,我无法让它读取变量“name”,而我需要这样做才能将字符串复制到节点。

最佳答案

您将 next_ptr 视为未声明,因为您尚未声明它。

你的代码应该是这样的......

linked_list   *next_ptr;
char          name_temp[MAX_SIZE];

while ((fscanf(sh_list, "%s", &name_temp)) !=EOF) {
         next_ptr = malloc(sizeof(linked_list));
         strcpy(next_ptr->name, name_temp);
         next_ptr->next_ptr = first_ptr;
         first_ptr = next_ptr;
} 

你还应该将链表中的名称声明为:

char      name[MAX_SIZE];

关于c - 在链表中存储行 (c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7479994/

相关文章:

java - 八叉树堆栈溢出错误

data-structures - 有没有这样的数据结构—— "linked list with samples"

c++ - C 和 C++ 的数组大小声明差异

c - 获取文件中元素的数量

c - gethostbyname() 函数返回空缓冲区

c++ - 为什么以及如何从接口(interface)定义语言 (IDL) 生成头文件

c++ - C++中的map数据结构是什么

javascript - 将对象数组转换为树形数据结构

c - 删除节点时出现无限循环

c - 获取链接列表中的先前值