【问题标题】:"warning: useless storage class specifier in empty declaration" in struct结构中的“警告:空声明中无用的存储类说明符”
【发布时间】:2016-09-10 19:40:44
【问题描述】:
typedef struct item {
    char *text;
    int count;
    struct item *next;
};

所以我有这个结构与上面定义的节点,但我得到下面的错误,我无法弄清楚什么是错的。

警告:空声明中的无用存储类说明符 };

【问题讨论】:

  • 你忘了给它命名:typedef struct item { char *text; int count; struct item *next; } tralalala;
  • 我认为在使用指针的结构中使用 typedef 是不可取的?我应该使用 typedef,即使我不会用它吗?
  • 一般来说,你不需要 typedef。将指针隐藏在 typedef 后面会更加混乱。

标签: c struct error-handling compiler-errors linked-list


【解决方案1】:

我不确定,但可以这样尝试:

typedef struct item {
  char *text;
  int count;
  struct item *next;
}item;

【讨论】:

  • struct item *next; 是否与将指针声明出结构大括号一样?
【解决方案2】:

typedef 用于为 C 中的现有类型创建简写符号。它类似于 #define,但不同的是,typedef 由编译器解释,并提供比预处理器更高级的功能。

typedef 的最简单形式为

typedef existing_type new_type;

例如,

typedef unsigned long UnsignedLong;

例如,如果你将size_t 的定义追溯到它的根,你会看到

/* sys/x86/include/_types.h in FreeBSD */
/* this is machine dependent */
#ifdef  __LP64__
typedef unsigned long       __uint64_t;
#else
__extension__
typedef unsigned long long  __uint64_t;
#endif
...
...
typedef __uint64_t  __size_t;   

然后

/* stddef.h */
typedef __size_t    size_t;

这实际上意味着,size_tunsigned long long 的别名,具体取决于您的机器具有的 64 位模式(LP64、ILP64、LLP64)。

对于您的问题,您尝试定义一个新类型但没有命名它。不要让struct item {..} 定义混淆您,它只是您要声明的类型。如果你用一个基本类型替换整个struct item {...},比如用int,然后重写你的typedef,你最终会得到这样的结果

typedef int; /* new type name is missing */

正确的形式应该是

typedef struct item {...} Item;

请参阅下面的示例了解不同的结构定义

#include <stdio.h>

/* a new type, namely Item, is defined here */
typedef struct item_t {
  char *text;
  int count;
  struct item_t *next; /* you canot use Item here! */
} Item;

/* a structure definition below */
struct item {
  char *text;
  int count;
  struct item *next;
};

/* an anonymous struct
* However, you cannot self-refence here 
*/
struct {
  int i;
  char c;
} anon;

int main(void) {
  /* a pointer to an instance of struct item */
  struct item *pi;

  /* Shorthand for struct item_t *iI */
  Item *iI;

  /* anonymoous structure */
  anon.i = 9;
  anon.c = 'x';
  return 0;
}

【讨论】:

    【解决方案3】:

    typedef 没用,因为你没有给它一个名字。您不能以任何方式使用 typedef。这就是你收到警告的原因,因为 typedef 没用。

    【讨论】:

      【解决方案4】:

      如果您像这样删除 typedef 关键字,该结构实际​​上仍然可以使用而没有警告:

      struct item {
          char *text;
          int count;
          struct item *next;
      };
      

      您只需要在变量声明中包含“struct”关键字。即

      struct item head;
      

      正如其他人指出的那样,如果您在结构定义的末尾包含名称,那么您可以将其用作 typedef,即使没有 struct 关键字,您也可以摆脱警告,但这会成为“项目”的第一个实例多余的即

      typedef struct {
          char *text;
          int count;
          struct item *next;
      } item;
      
      item head;
      

      也会消除警告。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-20
        • 1970-01-01
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多