Mahesha999
Mahesha999

Reputation: 24871

Unknown type name error in C

I am trying out some basic datastructure stuff in C. And I am coming back to C after a long time. Here is my simple struct:

typedef struct
{
    int data;
    LLNode *next; //Error: unknown type name 'LLNode'
}LLNode;

But it gives a compilation error as shown above. Is it because while compiling struct compiler is not aware of existence of LLNode? That means I must be first declaring LLNode before struct. Is it like that? If yes how I am supposed to do it?

Upvotes: 4

Views: 37565

Answers (4)

embedded
embedded

Reputation: 11

you can use:

typedef struct LLNode LLNode;
struct LLNode
{
int data;  
LLNode *next;   
};   

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

The data member next of the structure is declared the type LLNode, which is unknown.

The corrected example

typedef struct LLNode
{
    int data;
    struct LLNode *next; //Error: unknown type name 'LLNode'
}LLNode;

Take into account that the structure tag name and the typedef name are in different name spaces. So you may use these two names simultaneously like struct LLNode and just LLNode.

Upvotes: 6

jdarthenay
jdarthenay

Reputation: 3157

Do this that way:

typedef struct LLNode LLNode;

struct LLNode {
    int data;
    LLNode *next; //No error
};

You cannot use LLNode type before it is defined. With this method you declare what is LLNode first. Even though struct LLNode is not defined yet, this declaration suffice to declare LLNode * members (but you could not declare a LLNode member yet) as a pointer's size does not depend on the pointer's type.

Upvotes: 13

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The typedef is incomplete until the end, so LLNode is not available as a type name inside the struct. However, struct tag would be available, so you could do this:

typedef struct LLNode
{
    int data;
    struct LLNode *next;
} LLNode;

This produces a struct with an identical structure to what is in your post, because struct LLNode is typedef-ed to LLNode.

Upvotes: 2

Related Questions