C语言 如何在C中的结构内初始化const变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4676047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a const variable inside a struct in C?
提问by Celebi
I write a struct
我写了一个结构
struct Tree{
struct Node *root;
struct Node NIL_t;
struct Node * const NIL; //sentinel
}
I want
我想要
struct Node * const NIL = &NIL_t;
I can't initialize it inside the struct. I'm using msvs.
我无法在结构内初始化它。我正在使用 msvs。
I use C, NOT C++. I know I can use initialization list in C++.
我使用 C,而不是 C++。我知道我可以在 C++ 中使用初始化列表。
How to do so in C?
如何在 C 中这样做?
回答by templatetypedef
If you are using C99, you can used designated initializers to do this:
如果您使用的是 C99,则可以使用指定的初始化程序来执行此操作:
struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
This only works in C99, though. I've tested this on gcc and it seems to work just fine.
不过,这只适用于 C99。我已经在 gcc 上测试过了,它似乎工作得很好。
回答by Jonathan Wood
A structure defines a data template but has no data itself. Since it has no data, there's no way to initialize it.
结构定义了数据模板,但本身没有数据。由于它没有数据,因此无法对其进行初始化。
On the other hand, if you want to declare an instance, you can initialize that.
另一方面,如果你想声明一个实例,你可以初始化它。
struct Tree t = { NULL, NULL, NULL };
回答by gumby
Maybe something like this will suffice?
也许这样的事情就足够了?
struct {
struct Node * const NIL;
struct Node *root;
struct Node NIL_t;
} Tree = {&Tree.NIL_t};
回答by Erik Campobadal
For those seeking a simple example, here it goes:
对于那些寻求简单示例的人,这里是:
#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);
}
Produces the following output:
产生以下输出:
{ a: 10, b: 20 }

