How to initialize a const variable inside a struct in C?

≯℡__Kan透↙ 提交于 2019-12-29 05:59:06

问题


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.

I use C, NOT C++. I know I can use initialization list in C++.

How to do so in C?


回答1:


If you are using C99, you can used designated initializers to do this:

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.




回答2:


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



回答3:


Maybe something like this will suffice?

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



回答4:


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 }


来源:https://stackoverflow.com/questions/4676047/how-to-initialize-a-const-variable-inside-a-struct-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!