I'm trying to cast a struct
to another one. But I keep getting this error while compiling:
conversion to non-scalar type requested
I get the error for this line:
p is a struct prefix and i need to cast it to struct prefix_ipv4
get_info (type, (struct prefix_ipv4) p);
Code:
ospf_external_info_delete (u_char type, struct prefix_ipv4 p)
{
///////////////
}
struct prefix_ipv4
{
u_char family;
u_char prefixlen;
struct in_addr prefix __attribute__ ((aligned (8)));
}
struct prefix
{
u_char family;
u_char prefixlen;
union
{
u_char prefix;
struct in_addr prefix4;
struct in6_addr prefix6;
struct
{
struct in_addr id;
struct in_addr adv_router;
} lp;
u_char val[8];
} u __attribute__ ((aligned (8)));
};
Can anyone say why?
You can't cast to a different structure type. You can however cast to pointer to a different structure type, and this is widely done with structures that have common starting fields (the way yours do). You could change your function to take a pointer:
void get_info(..., struct prefix_ipv4 *prefix)
...
And then call it:
get_info(type, (struct prefix_ipv4 *)&p);
You cannot cast one struct type to another, even with an explicit cast. (Insert boilerplate flinching about implicit casting constructors and cast operator overloading.) You can cast a struct pointer to a different struct pointer, which is probably what you should be doing here; incidentally, you should also be passing your struct to the function by pointer.
You might want to look at the C 'union' keyword. It allows you to give alternative declarations for the same piece of memory.
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