c - 结构困惑

标签 c struct declaration definition

我已经有一段时间没有接触 C 语言了,所以我只是了解了一些概念,但找不到任何关于结构的好资料。

谁能解释一下

struct A
{
   int a;
   char b;
   float c;
};

这是结构A的声明还是定义。

最佳答案

它声明了一个带有结构标记 A 和指定成员的结构。它既不定义也不保留对象的任何存储空间。

来自 C99 标准,6.7 声明:

Semantics

5 A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

— for an object, causes storage to be reserved for that object;

— for a function, includes the function body; (footnote 98)

— for an enumeration constant or typedef name, is the (only) declaration of the identifier.

对于定义,您需要在最后一个分号之前提供一个对象标识符:

struct A
{
   int a;
   char b;
   float c;
} mystruct;

要同时初始化 mystruct,您可以编写

struct A
{
   int a;
   char b;
   float c;
} mystruct = { 42, 'x', 3.14 };

关于c - 结构困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761794/

相关文章:

c - 递归打印矩阵

c - 为什么此代码没有按预期打印小写字母?

c - 需要帮助创建可变长度数组

javascript - 重新声明一个javascript变量

C: const 初始值设定项和调试符号

此处不允许声明 JAVA 变量

c - 设置结构变量 - C

c - 如何使函数返回指向数组结构的指针

c++ - 具有预处理器分支实现的结构是否违反了 ODR?

c - 在 PostgreSQL 源代码中向缓冲区描述添加属性,现在出现自旋锁错误?