0

Im making a linked list using a typedef'ed struct, but the compiler is telling my that my new type is undefined.

typedef struct valholder
{
    char* id;
    union
    {
        int ival;
        float fval;
        char* cval;
    };
    valholder* next;
};

How do I fix this?

Chris Phillips
  • 1,997
  • 2
  • 19
  • 34

2 Answers2

2

The syntax for typedef is:

typedef <type> <alias>

Where <type> is an existing type name or a type expression (like struct {...}) and <alias> is the new type name.

Here's one way of defining your data strucure without referring to the alias:

typedef struct valholder_s {
  char* id;
  union {
     int ival;
     float fval;
     char* cval;
  };
  struct valholder_s* next;
} valholder;
didierc
  • 14,572
  • 3
  • 32
  • 52
  • 1
    The `_s` seems like an unnecessary change. – Jonathan Leffler Nov 13 '14 at 04:35
  • Why is it that valholder needs to be re-defined as a struct when it's already been typedef'd? – Chris Phillips Nov 13 '14 at 04:39
  • This is a habit I picked up from reading other people's code a long time ago. I guess that if the namespaces for structs and typenames are different maybe it isn't needed. – didierc Nov 13 '14 at 04:40
  • Actually I often happen a `_t` at the end of the alias to indicate that it's a typename, but here I chose to stick to OP's choice. – didierc Nov 13 '14 at 04:48
  • @ChrisPhillips the typedef happens after the struct definition, see http://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions for a far better explanation. – didierc Nov 13 '14 at 04:52
1

Try this:

   typedef struct valholder
    {
        char* id;
        union
        {
            int ival;
            float fval;
            char* cval;
        };
        struct valholder* next;
    } valholder;
Dmitri
  • 9,175
  • 2
  • 27
  • 34
Wilson
  • 251
  • 3
  • 9