开发者

Initialize unnamed struct pointer/array

struct A
{
    int member1;
    int member2;
    struct B
    {
        int member3;
        int member4;
    } *b;
};

How can I initialize A and at the same time create an array of B's to fill the b 开发者_如何转开发field? I want a static variable, so preferably function calling.

I tried this but it does not work (I didn't think it would):

static A a = {
    1,
    2,
    & { {3, 4}, {5, 6} },
}


I think the problem with this code is this line:

& { {3, 4}, {5, 6} }

The problem is that {{3, 4}, {5, 6}} is an rvalue (a value, not an object) and you can't take the address of an rvalue. After all, where is the memory for this object going to come from? However, you might be able to get away with rewriting this to

A::B elems[2] = {{3, 4}, {5, 6}};
static A a = {
    1,
    2,
    elems
};

Since now you have an lvalue you can point at.


You have tagged this with both C and C++; the following answer is for C.

In C89, you can do:

static struct B a_b_init[] = { {3, 4}, {5, 6} };
static struct A a = {
    1,
    2,
    a_b_init
};

In C99, you can use a compound literal, which has very similar syntax to your attempt:

static struct A a = {
    1,
    2,
    (struct B []){ {3, 4}, {5, 6} }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜