简体   繁体   English

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

[英]How to initialize a const variable inside a struct in C?

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++. 我使用C,而不是C ++。 I know I can use initialization list in C++. 我知道我可以在C ++中使用初始化列表。

How to do so in C? 如何在C中这样做?

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. 但这仅适用于C99。 I've tested this on gcc and it seems to work just fine. 我已经在gcc上测试了它,它似乎工作得很好。

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 };

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 }

Maybe something like this will suffice? 也许这样的事情就足够了?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM