【问题标题】:Structure declaration and definition in CC中的结构声明和定义
【发布时间】:2018-09-09 00:09:58
【问题描述】:

如果我们这样写:

typedef struct 
{
    unsigned int counter;
} MyStruct;

这代表结构声明?

声明告诉我们的编译器,在某处有一个结构,其具有上述类型和大小的参数,并且在声明的情况下,不会在内存中为该结构保留空间。

定义是,现在我们在内存中为我们的结构保留了一个空间:

MyStruct tmpStruct;

还是我错了?

请用结构说明情况。

【问题讨论】:

  • 注意标签...它是 C 或 C++ 而不是 CSS ...
  • 是的,对不起,我是用手机写的。
  • 对于您的问题,您在某种程度上是正确的...首先您定义一个新类型,因此内存中没有任何内容,然后当您使用此类型声明变量时,您将在内存中分配所需的空间跨度>

标签: c struct compilation declaration definition


【解决方案1】:

C 中有不同种类的定义——类型定义、变量定义和函数定义。类型和函数也可以在没有定义的情况下声明。

你的typedef 不是一个声明,它是一个类型的定义。除了定义不带标签的struct 之外,它还定义了与struct 对应的类型名称。

struct 的声明如下所示:

typedef struct MyStruct MyStruct;

这将允许您声明指向MyStruct 的指针、前向声明采用MyStruct* 的函数等等:

void foo(MyStruct* p);

您所拥有的是MyStruct 类型变量的声明/定义:

MyStruct tmpStruct;

这是一个完整的例子,struct 的声明与其定义分开:

#include <stdio.h>
// Here is a declaration
typedef struct MyStruct MyStruct;
// A declaration lets us reference MyStruct's by pointer:
void foo(MyStruct* s);
// Here is the definition
struct MyStruct {
    int a;
    int b;
};
// Definition lets us use struct's members
void foo(MyStruct *p) {
    printf("%d %d\n", p->a, p->b);
}

int main(void) {
    // This declares a variable of type MyStruct
    MyStruct ms = {a:100, b:120};
    foo(&ms);
    return 0;
}

Demo.

【讨论】:

  • 这读起来像是超出了问题级别的“高级用户指南”。 struct 初始化中不必要的 a:b: 是什么?
  • @WeatherVane 我想我会包含a:b: 来让读者对指定的初始化程序感到好奇——这个功能已经存在了一段时间,但还没有得到广泛使用。就OP的理解程度而言,我无法通过一个帖子来弄清楚。
  • 一切都很好,但您似乎与 OP 的信念相矛盾,这基本上是正确的。
  • @WeatherVane 好吧,我不应该说 OP 的观点是完全正确的,尽管它肯定不是不正确的。我想我应该向他提一些重要的事情来完成他对 C 世界的描绘。
  • 结构的声明看起来不像,那是 typedef 声明!结构的声明只是 struct tagname { members...};如果你实例化它,你会保留 struct 这个词。
【解决方案2】:

这里有一篇很棒的文章

https://www.microforum.cc/blogs/entry/21-how-to-struct-lessons-on-structures-in-c/

您声明的第一件事是类型声明与结构声明相结合,没有定义,因此没有正确分配空间。

声明结构的正确方法是:

   struct MyStruct
   {
      unsigned int counter; 
   };

您现在可以像这样定义实例:

   struct Mystruct myVariableStructInstance = {1234};  // Define struct instance with initializer

也可以将声明与这样的定义结合起来:

   struct MyStruct_t
   {
      unsigned int counter; 
   }  MyStructVariable;

这将声明结构类型 (struct MyStruct_t) 并为您定义/实例化一个名为 MyStructVariable 的结构变量

您现在可以将 MyStructVariable 传递给这样声明的函数:

void myFunction(struct MyStruct_t  temp);

你会简单地调用它

myFunction(MyStructVariable);

但是说真的,阅读那篇博文,它解释的远不止这些!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2015-07-21
    • 2014-04-17
    相关资源
    最近更新 更多