简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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