[英]How to initialize a const variable inside a struct in C?
我寫了一個結構
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中這樣做?
如果您使用的是C99,則可以使用指定的初始化程序來執行此操作:
struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
但這僅適用於C99。 我已經在gcc上測試了它,它似乎工作得很好。
結構定義了數據模板,但本身沒有數據。 由於它沒有數據,因此無法對其進行初始化。
另一方面,如果要聲明實例,可以初始化它。
struct Tree t = { NULL, NULL, NULL };
對於那些尋求簡單例子的人來說,這里是:
#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 }
也許這樣的事情就足夠了?
struct {
struct Node * const NIL;
struct Node *root;
struct Node NIL_t;
} Tree = {&Tree.NIL_t};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.