链表中的商店线(c)

时间:2011-09-20 04:01:58

标签: 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
    }
};

我停在//移动...因为我正在努力让代码正确 - 我的IDE给了我错误。同样,我不能让它读取我需要做的变量“name”,以便将字符串复制到节点。

3 个答案:

答案 0 :(得分:1)

你将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];

答案 1 :(得分:0)

fscanf语句中,您指定输入字符串%s,但name_temp的类型为char。您将不得不将其更改为char数组,如下所示:

char name_temp[100];

为了您的目的,您必须使阵列足够大。您还必须更改name的类型:

char name[100];

您收到的错误是因为namenext_ptr是结构linked_list的一部分,但您必须创建linked_list的实例化才能访问{{1} }}。在您的情况下,您拥有name,因此您应将其更改为:

current_ptr

答案 2 :(得分:0)

应为strcpy(current_ptr->name, name_temp);

您正在尝试引用结构中的name变量,该变量需要通过current_ptr进行访问。

同样应该是current_ptr->next_ptr = malloc(sizeof(linked_list));

要访问结构中的变量,您需要使用.运算符。当您使用指向结构的指针时,可以使用->运算符访问其变量。

相关问题