I've been browsing stackoverflow concerning the problem of initialising a union in a struct but I didn't manage to get it right.
Here is my struct
typedef struct dc_netif_filter {
unsigned char filter_type;
union {
uint32_t itf_nb;
char * buf;
} value;
} dc_netif_filter_t;
In my code, i have tried to use :
dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME,{{0, "tun"}}};
which gives error: braces around scalar initializer for type ‘uint32_t’
and
dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME,{0, "tun"}};
which gives error: too many initializers for ‘dc_netif_filter::< anonymous union>’
How do i declare such a dc_netif_filter_t ?
I'm using g++ on ubuntu. Note that the dc_netif_filter_t isn't a struct that I can modify as it comes from a third party project.
**EDIT : as I've been explained, i can only initialise one field. The problem is that with
dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME,"tun0"};
I get a conversion error : invalid conversion from ‘const char*’ to ‘uint32_t
Thanks
As the compiler says, too many initializers for ‘dc_netif_filter::< anonymous union>’.
Initialize only one field, not both.
Use the name of the field to initialize it properly:
dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME, { buf: "tun0" }};
It looks like you are trying to initialize your structure to indicate that the buf member is to be used, and that the value of that buf should be "tun". Since C++ before C++11 lacks designated initializers, you cannot do it with an initializer: only the first field of the union can be initialized, so you need to do your assignment in code:
static get_dc_netif_filter_t() {
static c_netif_filter_t netif = {DC_NETIF_SELECT_NAME, {0}};
if (netif.value.itf_nb == 0) {
netif.value.buf = "tun";
}
return netif;
}
C++11 lets you do it like this:
dc_netif_filter_t netif = {DC_NETIF_SELECT_NAME, { .buf = "tun"}};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With