Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 795
Mahesha999 Avatar asked Oct 18 '25 14:10

Mahesha999


2 Answers

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.

like image 79
jdarthenay Avatar answered Oct 20 '25 06:10

jdarthenay


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.

like image 27
Vlad from Moscow Avatar answered Oct 20 '25 06:10

Vlad from Moscow