Thread: Typedefing Unions

  1. #1
    Old Fashioned
    Join Date
    Nov 2016
    Posts
    137

    Typedefing Unions

    In K&R C, there is a syntax used to typedef unions that gcc isn't liking. I have this code:

    Code:
    typedef union header{
     typedef struct S{
      unsigned int size;
      union header *next;
      
     }s;
     long padding;
    }Header;
    I'm then using code like this, where block_pointer is a pointer to a Header struct:
    Code:
    block_header->s.size
    And I get "Header has no member named s." I'm not sure what I'm doing wrong here but I suppose it has to do with the union or the struct definition. Strangely, a similar format is used in K&R C which works fine.

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    You can't nest typedefs. You need to do it in two steps.
    And s is not an object anyway. It's just a type.
    Code:
    union header;  // forward reference
    
    typedef struct S {
      unsigned int size;
      union header *next;
    } s;
    
    typedef union header {
      s q;
      long padding;
    } Header;
    
    int main() {
      Header header, *block_header = &header;
      block_header->q.size = 1;
      return 0;
    }
    Alternatively, you can just leave out the typedef of the inner struct since it's probably useless anyway.
    Code:
    typedef union header {
      struct S {
        unsigned int size;
        union header *next;
      } s;  // now this is an object, not just a type
      long padding;
    } Header;
    
    int main() {
      Header header, *block_header = &header;
      block_header->s.size = 1;
      return 0;
    }
    Last edited by algorism; 08-30-2017 at 10:31 PM.
    Explode the sunlight here, gentlemen, and you explode the entire universe. - Plan 9 from Outer Space

  3. #3
    Old Fashioned
    Join Date
    Nov 2016
    Posts
    137
    Aha! Thank you algorism! That has always been some of the most confusing part of C for me... struct, union, and enum declarations vs. typedefs. I forget that without typedef, you're declaring the s as a struct s versus with typedef you're aliasing it. This has always been more confusing to me than even pointers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unions.
    By Mr.Lnx in forum C Programming
    Replies: 13
    Last Post: 06-12-2013, 04:51 PM
  2. Typedefing function pointers
    By sakura in forum C Programming
    Replies: 3
    Last Post: 09-06-2012, 02:05 AM
  3. different ways of typedefing
    By dayalsoap in forum C Programming
    Replies: 8
    Last Post: 09-14-2010, 05:35 AM
  4. Unions?
    By Sure in forum C Programming
    Replies: 8
    Last Post: 06-30-2005, 02:47 AM
  5. Quick Q - Typedefing integers
    By Verdagon in forum C++ Programming
    Replies: 2
    Last Post: 04-30-2005, 08:28 PM

Tags for this Thread