Difference between cast of structures

3
struct a{

   int a;
   int b;
};

struct b{

  int a;
  int b;

}

int main()
{

   struct a *p;

   struct b b;

  p = (struct a *)b; // deste modo da erro

  p = (struct a *)&b; ; deste modo o compilador não aponta erro;

}

Would you like to know why?

    
asked by anonymous 31.01.2016 / 22:09

1 answer

2

(struct a *)b is taking a structure and casting cast to a pointer to a structure . That's not possible. A pointer is something very different from a structure.

In this case you are trying to put a structure with two integers inside a pointer. It does not fit. The main point of type struct a * is that it is a pointer. For what it points out is important, but secondary. Primarily it is a pointer.

(struct a *)&b is getting an address for a structure, which is a pointer, and casting cast for a pointer to a structure . It is possible. They are incompatible types, and pointer to pointer.

The & is the operator that takes the address of something, that is, it generates a data that will potentially be a pointer, but will never be a structure.

    
31.01.2016 / 22:18