0

I have the following code. Why its undefined to derefrence union pointers in the following way ?

extern union MyUn *P1;          
extern union MyUn *P2;

extern void myfunc(void)
{
      *P1 = *P2;                
}
Mat
  • 202,337
  • 40
  • 393
  • 406
bubble
  • 3,408
  • 5
  • 29
  • 51

2 Answers2

7

If you haven't also defined the union in this source file, the compiler doesn't know how much to copy.

What is the size of the union?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • If the union isn't known at that point, won't `*P1` and `*P2` be incomplete types ? Thus the dereference itself is not OK. – cnicutar Sep 01 '12 at 09:41
  • Yes, the main problem with incomplete `struct` and `union` types is that they are of unknown size (and contain unknown members). – Bo Persson Sep 01 '12 at 09:51
3

That has nothing to do with unions in particular, and it's not "undefined", either: It's simply a compiler error if you try to dereference a pointer to an incomplete type (for obvious reasons).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084