0

I have a struct for a linked list in my C code. When the list is defined like this:

typedef struct LinkedList {
    Ht_item* item;
    LinkedList* next;
}LinkedList;

I get the Compilation Error: "error: unknown type name ‘LinkedList’" alongside other related error messages

However, when i define my LinkedList this way:

typedef struct LinkedList LinkedList;

struct LinkedList {
    Ht_item* item;
    LinkedList* next;
};

I get no errors.

I do not understand why the Error happens in the first instance?

  • OT: It's only a special case when a single node is the entire list... Please call a node a "node", and name the variable(s) that point to the head (and tail?) node(s) of the list a "list"... A single "link" is rarely referred to as "a chain"... – Fe2O3 Jan 14 '23 at 04:31
  • You can't refer to a `typedef` until after the type definition is completed. That's not until the end of the structure definition. – Barmar Jan 26 '23 at 03:46

1 Answers1

1

In this definition:

typedef struct LinkedList {
    Ht_item* item;
    LinkedList* next;
}LinkedList;

You're using the type LinkedList before it's been defined or declared.

This works:

typedef struct LinkedList LinkedList;

struct LinkedList {
    Ht_item* item;
    LinkedList* next;
};

Because LinkedList has been declared (but not fully defined) by the time it's used, and because you're creating a pointer to that type it doesn't need to be fully defined yet.

This would also work:

typedef struct LinkedList {
    Ht_item* item;
    struct LinkedList* next;
}LinkedList;

For the same reason the prior piece of code works.

dbush
  • 205,898
  • 23
  • 218
  • 273