【发布时间】:2013-07-19 09:05:40
【问题描述】:
我有一个这样的结构:
typedef struct tree_s{
struct tree_s *a;
int b;
}tree_t;
目前,我正在以这种方式进行初始化:
tree_t branch_n = {
.a = NULL,
.b = 2
};
tree_t root = {
.a = (tree_t*) &branch_n,
.b = 1
};
现在,我不得不在根之前初始化较低的分支,这让我很恼火,因为完整的结构非常大,分支都有自己的分支,这使得我的代码难以管理。
我想做的是这样的:
tree_t root = {
.a =
//The first branch
{
.a =
//Yet another branch
{ //Since the following is actually an array, I need the
// "a" above to point to the first index
{
.a = NULL, //Maybe this will have its own branch
.b = 3
},
{
.a =
{
.a = NULL, //And this might even have its own branch
.b = 5
}
.b = 4
}
}
.b = 2
},
.b = 1
};
我怎样才能实现这样的初始化?
我想这样做的主要原因是为了大大增强我的代码概览,并立即直观地看到“树”的结构。
请注意,从一开始就知道完整“树”的结构,这就是我认为结构不变的原因。但是 b 的值可以随时更改。
我对 C 语言很陌生,这是我在 SO 上的第一篇文章,所以请随时编辑或询问我是否无法让自己清楚:)
【问题讨论】:
-
那么问题是什么?
-
我认为为此你应该将结构声明为
typedef struct tree_s{ struct tree_s a; int b; }tree_t; -
lulyon:对不起,我已经编辑包含一个实际问题:)。我无法以我想要的方式进行初始化(示例)。 Grijesh:我的编译器(IAR Embedded Workbench)收到错误“不允许不完整类型”:/
-
您不能像 Grijesh 的评论那样声明结构;您只能声明一个包含指向其自身类型的指针的结构。
标签: c data-structures struct constants typedef