【问题标题】:How to initialize a const variable inside a struct in C?如何在 C 中的结构内初始化 const 变量?
【发布时间】:2011-06-08 05:50:48
【问题描述】:

我写了一个结构

struct Tree{
    struct Node *root;
    struct Node NIL_t;
    struct Node * const NIL;    //sentinel
}

我想要

struct Node * const NIL = &NIL_t;

我无法在结构中初始化它。 我正在使用 msvs。

我使用 C,而不是 C++。 我知道我可以在 C++ 中使用初始化列表。

如何在 C 中做到这一点?

【问题讨论】:

  • 出于好奇,为什么需要 NIL_t 的值和指向 NIL 的指针?这似乎有点多余。独立地,这是一个有趣的问题!
  • 正确。你没有使用 C++,这就是你不能这样做的原因。

标签: c struct initialization constants


【解决方案1】:

对于那些寻求简单示例的人来说,这里是:

#include <stdio.h>

typedef struct {
    const int a;
    const int b;
} my_t;

int main() {
   my_t s = { .a = 10, .b = 20 };
   printf("{ a: %d, b: %d }", s.a, s.b);
}

产生以下输出:

{ a: 10, b: 20 }

【讨论】:

    【解决方案2】:

    也许这样就足够了?

    struct {
        struct Node * const NIL;
        struct Node *root;
        struct Node NIL_t;
     } Tree = {&Tree.NIL_t};
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 C99,则可以使用指定的初始化程序来执行此操作:

      struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
      

      不过,这只适用于 C99。我已经在 gcc 上对此进行了测试,它似乎工作得很好。

      【讨论】:

      • +1 这实际上是一个很好的宏:#define TreeDecl(id, rt) struct Tree id = { .root = rt, .NIL = &amp;id.NIL_t }
      • 在 C89 中,您可以执行 struct Tree t = { NULL, { 0 }, &amp;t.NIL_t };,只要 0 是结构节点中第一个字段的有效初始值设定项。
      • 或者,根据@Chris Dodd 的评论,您可以重新排列结构,使NIL 成员位于NIL_t 成员之前,然后使用struct Tree t = { NULL, &amp;t.NIL_t };
      【解决方案4】:

      结构定义了数据模板,但本身没有数据。由于它没有数据,因此无法对其进行初始化。

      另一方面,如果你想声明一个实例,你可以初始化它。

      struct Tree t = { NULL, NULL, NULL };
      

      【讨论】:

      • NIL_tstruct Node,而不是struct Node *,所以它可能不会被初始化为NULL。我还建议您创建一个 struct Tree *init(...) 函数(或者如果您愿意,可以使用一个 void init(struct Tree *t, ...) 函数或宏)来为您完成此类工作。
      • @Chris:没错。一定是错过了。我猜你可能只能在声明两个结构后才能将一个结构分配给另一个结构。
      • @Jonathan - 对于嵌套的structs,你可以使用struct Tree t = { NULL, { /* struct Node contents here */ }, NULL }(或者&amp;t.NIL_t作为最后一个。)
      • @Chris:我一开始就是这么想的。但如果该成员是同一类型的结构,则语法将是无限递归的。不,我认为这行不通。
      • @Jonathan - 他们不是。这是struct Tree 中的struct Node。在这种情况下不是无限递归的。 (如果它是无限递归的,这将是一个问题。但这不是 OP 的情况。)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 2013-01-17
      • 2012-03-30
      相关资源
      最近更新 更多