Reputation: 409
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?
Upvotes: 7
Views: 16603
Reputation: 1135
Since you have so little data you should just initialise a struct prefix_ipv4
from struct prefix
and pass that.
Or go with the pointer answer, but in the case that the function prototype is easily modified without repercussions I'd be replacing struct prefix_ipv4
with struct prefix
as I don't see the need for the ipv4 version which the ipv6 version can handle.
Upvotes: 0
Reputation: 16328
p
is probably a pointer and the error says you cannot cast a pointer to a structure type. If the argument to ospf_external_info_delete
was a pointer instead, then you can cast a type pointer to another type pointer.
Upvotes: 1
Reputation: 14471
You might want to look at the C 'union' keyword. It allows you to give alternative declarations for the same piece of memory.
Upvotes: 2
Reputation: 182639
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);
Upvotes: 12
Reputation: 41474
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.
Upvotes: 5