如何在C中初始化结构内的const变量?

Cel*_*ebi 13 c struct initialization const

我写了一个结构

struct Tree{
    struct Node *root;
    struct Node NIL_t;
    struct Node * const NIL;    //sentinel
}
Run Code Online (Sandbox Code Playgroud)

我想要

struct Node * const NIL = &NIL_t;
Run Code Online (Sandbox Code Playgroud)

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

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

如何在C中这样做?

tem*_*def 23

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

struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
Run Code Online (Sandbox Code Playgroud)

但这仅适用于C99.我已经在gcc上测试了它,它似乎工作得很好.

  • 在C89中,您可以执行`struct Tree t = {NULL,{0},&t.NIL_t};`只要0是结构节点中第一个字段的有效初始值设定项. (4认同)