简体   繁体   English

如何使用匿名数组初始化结构

[英]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};错误:获取临时数组的地址 (uint16_t[]){0xfdaa, 0, 0, 0, 0, 0, 0, 1};

and also并且

error: expected primary-expression before '{' token CIpv6Address {错误:“{”令牌 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.但我不想用new分配一个数组,因为它需要在之后以某种方式delete 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.这不是您在 C 中初始化变量的方式。 In C initialization has a form like type variable = value - there has to be a = between the name of the variable and { .在 C 中,初始化的形式类似于type variable = value - 在变量名称和{之间必须有一个= Also without the use of typedef you have to use the keyword struct in front of the name.此外,如果不使用typedef ,您必须在名称前使用关键字struct

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.在文件 scope 复合文字具有 static 存储持续时间,但在块 scope 它们具有自动存储持续时间 - 与往常一样,您必须注意对象的生命周期。 You can godbolt link :您可以使用godbolt链接

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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