简体   繁体   中英

How to initialize struct with anonymous array

I'm trying to create nested structs with anonymous array initialization:

struct CIpv6Address {
    uint16_t* address;
};

struct CIpv6Cidr {
    CIpv6Address* address;
    uint16_t cidr;
};

CIpv6Cidr cIpv6Cidr1{
    CIpv6Address {
        (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};
    },
    64
};

but I'm getting:

error: taking address of temporary array (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};

and also

error: expected primary-expression before '{' token CIpv6Address {

The first error I kinda know why. But I don't want to allocate an array with new as it'd need to be delete d somehow after. Is there a simple way to simply put a little address there?

And for the second error I have no idea

That's not how you initialize variables in C. In C initialization has a form like type variable = value - there has to be a = between the name of the variable and { . Also without the use of typedef you have to use the keyword struct in front of the name.

How to initialize struct with anonymous array

You can use compound literals. At file scope compound literals have static storage duration, but at block scope they have automatic storage duration - as always you have to watch out for lifetime of objects. You can godbolt link :

#include <stdint.h>

struct CIpv6Address {
    uint16_t* address;
};

struct CIpv6Cidr {
    struct CIpv6Address* address;
    uint16_t cidr;
};

struct CIpv6Cidr cIpv6Cidr1 = {
    &(struct CIpv6Address){
        (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1},
    },
    64
};

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