我认为我在链表的工作方式上遇到了一些问题,请记住我不是 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/