【问题标题】:Creating multiple linked lists in C在 C 中创建多个链表
【发布时间】:2021-04-24 01:46:37
【问题描述】:

您好,我在一些 C 编程方面遇到了一些麻烦。我正在尝试创建多个类名链接列表。

我目前有:

struct class_list {
    char name[20];
    struct class_list *next;
} *class;

class setup_new() {
    class start;
    *start = NULL;
    start = malloc(sizeof(*start));
    if (start == NULL)
        printf("error");
    return start;
}

但它起作用了,我不知道为什么。

【问题讨论】:

  • 它不起作用怎么办?您遇到了什么行为?
  • 理想情况下,您应该为这个结构指针使用除 class 之外的名称,因为这是 C++ 中的保留关键字,可能会让人感到困惑。
  • 有隐藏的typedef吗?对结构使用 typedef 是个坏主意,在你的问题中不包括 typedef 更糟糕。
  • @jarmod 但这是一个 C 问题,因此 class 是完全合法的。
  • @WilliamPursell - “对结构使用 typedef 是个坏主意”,可能是因为 struct 用于链表,但声明太强而无法使用作为关于typedef struct的一般性声明

标签: c linked-list


【解决方案1】:

有多个问题:

  • 您将class 定义为全局变量,但将其用作typedef,导致语法错误。

  • 您使用*start = NULL 取消引用未初始化的指针class。这具有未定义的行为。

请注意,避免将 C++ 关键字作为 C 标识符并避免将指针隐藏在 typedef 后面会更易读且问题更少。

这是修改后的版本:

#include <stdio.h>
#include <stdlib.h>

struct class_list {
    char name[20];
    struct class_list *next;
} *class_head;

struct class_list *setup_new(void) {
    struct class_list *start = malloc(sizeof(*start));
    if (start == NULL)
        printf("error\n");
    return start;
}

【讨论】:

    【解决方案2】:

    你可能想要这个:

    struct class_list {
      char name[20];
      struct class_list* next;
    };
    
    struct class_list *setup_new() {
      struct class_list *start;
      // this is wrong and pointless: *start = NULL;
      start = malloc(sizeof(*start));
      if (start == NULL)
        printf("error");
      return start;
    }
    

    或者这基本上是一样的:

    typedef struct class_list {
      char name[20];
      struct class_list* next;
    } class;
    
    class *setup_new() {
      class *start;
      // this is wrong and pointless: *start = NULL;
      start = malloc(sizeof(*start));
      if (start == NULL)
        printf("error");
      return start;
    }
    

    或者甚至是这样:

    typedef struct class_list {
      char name[20];
      struct class_list* next;
    } *class;
    
    class setup_new() {
      class start;
      // this is wrong and pointless: *start = NULL;
      start = malloc(sizeof(*start));
      if (start == NULL)
        printf("error");
      return start;
    }
    

    我不推荐最后一种可能性,因为这里我们在 typedef 后面隐藏了一个指针类型,这通常会引起混淆。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-18
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 2013-10-09
      相关资源
      最近更新 更多