【问题标题】:using structures in GCC and getting errors在 GCC 中使用结构并出现错误
【发布时间】:2011-09-23 05:36:27
【问题描述】:

相同的代码在 TURBO C 中运行。

    struct details
    {
      char name[20];
      int year;
      float price;
    }my_str;

    details book1[10];

产生此错误。如何解决这个问题?

ram.c: In function ‘main’:
ram.c:11:1: error: ‘details’ undeclared (first use in this function)
ram.c:11:1: note: each undeclared identifier is reported only once for each function it appears in

【问题讨论】:

  • 出现错误的原因是在 C++ 中允许像上面那样编写,但在 C 中不允许。我的猜测是 Borland 在转向 C++ 时添加了它作为 Turbo C 的扩展。

标签: c gcc compilation struct


【解决方案1】:

有两种方法可以解决这个问题:

将第二行改为:

struct details book1[10];

或者您可以将声明更改为:

typedef struct{
    char name[20];
    int year;
    float price;
} details;

C 与 C++ 略有不同,因此您不能以完全相同的方式声明结构。

【讨论】:

    【解决方案2】:
    details book1[10];
    

    需要...

    struct details book1[10];
    

    【讨论】:

      【解决方案3】:

      你需要像这样声明结构变量:

      struct details book1[10];
      

      这是因为details 不是typedefed,因此不能像用户定义的类型那样使用它,因此需要使用struct 关键字。

      请注意,在您的上述定义中,my_strstruct details 类型的变量(已分配对象)

      你也可以这样做:

      typedef struct details
      {
        char name[20];
        int year;
        float price;
      } my_str;
      

      然后做:

      my_str book1[10];
      

      这和上面一样。请注意,my_str 不是变量(对象),而是您使用 typedef 关键字定义的类型名。此后,编译器将知道您正在使用my_str 作为您创建的复合结构数据类型的新用户定义类型名称,因此您可以直接使用my_str 而不是使用struct details

      【讨论】:

        【解决方案4】:

        这在 C 方面更正确:

        typedef struct _detailstype
        {
          char name[20];
          int year;
          float price;
        } details;
        
        
        details book1[10];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-05-09
          • 1970-01-01
          • 2020-08-04
          • 1970-01-01
          • 2015-12-27
          • 2020-08-02
          • 1970-01-01
          相关资源
          最近更新 更多