【问题标题】:store line in linked list (c)在链表中存储行 (c)
【发布时间】:2011-09-20 12:23:32
【问题描述】:

我认为我对链表的工作方式存在一些问题,请记住,我不是 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”是函数 writeList 中的一个未识别变量。除此之外,我一直在寻找一些建议,以找到正确的方向,以便将这个东西存储在一个链表中。
  • 您可能需要一个数组作为名称:char name[36]; 或附近(选择您的大小)。这需要在结构中;您还在函数中引用了一个变量name,但没有提供它的定义;你还有char name_temp;,它应该(a)在函数内部,(b)也应该是一个数组。您应该在格式中指定数组的大小减一(例如"%35s")。
  • 不要在函数定义末尾的大括号后放置分号。

标签: c data-structures linked-list


【解决方案1】:

您将 next_ptr 视为未声明,因为您没有对其进行 declared。

您的代码应该如下所示...

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

【讨论】:

  • 这帮助很大,它解决了我遇到的所有错误 - 谢谢:)。我将继续插电,但理论上这会将每一行存储在链表中?另外,真正阅读链表及其内部工作原理的最佳地点在哪里,显然我并没有像我应该的那样理解它们(我知道这一点)
【解决方案2】:

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

char name_temp[100];

您必须使数组足够大以满足您的目的。您还必须更改name 的类型:

char name[100];

您遇到的错误是因为namenext_ptr 是结构linked_list 的一部分,但您必须创建linked_list 的实例化才能访问name。在你的情况下,你有 current_ptr 所以你应该把它改成:

current_ptr->next_ptr = malloc(sizeof(linked_list));
strcpy(current_ptr->name, name_tmp);

【讨论】:

  • 你知道为什么它告诉我 next_ptr 是未声明的吗?
  • @SoFly 与未声明 name 的原因相同。 next_ptr 是结构的一部分,您必须创建结构的实例化才能访问next_ptr 的副本。
  • 它们仍未声明,所以我需要在函数内部创建某种引用来访问结构的变量?
  • 因为next_ptr 没有声明为变量。如果要引用结构的元素,则必须有要引用的结构:linked_list item; item.next_ptr = malloc(...);。即使解决了这个问题,您也可能需要解决一些先有鸡还是先有蛋的问题。
【解决方案3】:

应该是strcpy(current_ptr->name, name_temp);

你试图引用结构中的name变量,需要通过current_ptr来访问。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多