c - 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
};
推荐阅读
- ubuntu - 在 oom-killer 日志中启用顶级进程登录
- javascript - 在同一个表中更新和删除
- javascript - React Native Expo 请求失败,状态码为 404
- r - 查找峰的最近邻对的索引
- c# - 使用模式解析字符串中的值
- linux - 带有 PHP 7.2 Pthreads 的 Centos 7 无法加载 redis.so
- angular - 初始化:
列排序 - sharepoint - 如何将文档从 SharePoint 2016 文档库移动到 SharePoint 2010 文档库?
- javascript - 在两个输入中显示/隐藏密码
- c# - 使用 Roslyn 生成代码时,如何在一行上获得自动属性?