Thread: Union of a struct

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    15

    Union of a struct

    I have this piece of code:
    Code:
    #define NFIELDS 4
    
    typedef union 
    {
       int Par[NFIELDS];
       struct {
          int Field1;
          int Field2;
          int Field3;
          int Field4;
       };
    } Par_t;
    Every time I add a new field in the struct I have to manualy set NFIELD to the right number. Every field of the struct is always int so you can access the single field or you can access through the array.
    How can I get rid of the macro NFIELDS and use instead the size of the struct to avoid errors when I add a new field inside the struct?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    This should do it.
    Code:
    #include <stdio.h>
    
    typedef union
    {
       struct foo {
          int Field1;
          int Field2;
          int Field3;
          int Field4;
       } Sar;
       int Par[sizeof(struct foo)/sizeof(int)];
    } Par_t;
    
    int main()
    {
        Par_t   p;
        printf("%zd\n", sizeof(p));
        printf("%zd\n", sizeof(p.Sar));
        printf("%zd\n", sizeof(p.Par));
        return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2020
    Posts
    15
    This is a good solution, Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Union and struct arrays
    By Crossfire in forum C Programming
    Replies: 17
    Last Post: 10-25-2013, 04:47 PM
  2. Union and struct
    By sick in forum C Programming
    Replies: 1
    Last Post: 01-11-2009, 06:22 PM
  3. struct vs. union
    By Draco in forum C Programming
    Replies: 2
    Last Post: 08-29-2003, 07:09 AM
  4. Union in a struct?
    By Hunter2 in forum C Programming
    Replies: 2
    Last Post: 06-13-2003, 11:45 AM
  5. More Union Struct woes
    By Bajanine in forum C++ Programming
    Replies: 10
    Last Post: 04-19-2003, 02:20 PM

Tags for this Thread