Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a struct to another

Tags:

c++

c

struct

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?

like image 204
user2714949 Avatar asked Sep 25 '13 12:09

user2714949


3 Answers

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);
like image 114
cnicutar Avatar answered Nov 07 '22 17:11

cnicutar


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.

like image 26
Sneftel Avatar answered Nov 07 '22 16:11

Sneftel


You might want to look at the C 'union' keyword. It allows you to give alternative declarations for the same piece of memory.

like image 2
Jay Avatar answered Nov 07 '22 16:11

Jay