Compilation Error: dereferencing pointer to incomplete type

I am getting a dereferencing pointer to incomplete type error when i compile the following code on lines highlighted in red. Can anyone help me in identifying what is wrong in the code?

#include<stdio.h>
#include<stdlib.h>

typedef struct{
int info;
struct node* link ;
} node;

void main(){
struct node* head;
head = (struct node *) malloc (sizeof(struct node* ));
head->info = 10;
head->link = NULL; 
}

There are many things wrong with your code...the struct typedef lacks a struct tag...and you are mallocing memory for a pointer to that struct instead of a struct object. Fixing these two things should give you a clean compilation...

can you please explain in simple terms what is wrong.. and how to correct it?

See in bold.

First, you forgot the struct name, so after "typedef struct" I added "node". This makes it "struct node". This is where you were having the "undefined type" problems, because "struct" without "node" is just an anonymous typedef'd struct.

The second change, I like to suffix typedef'd types with "_t" so they are known to be types. This doesn't have to be your style, but it helps clarify in the rest of the code that you can use either "struct node" or "node_t" to define "objects" of types "node_t". Essentially, the compiler makes "struct node" and "node_t" synonymous.

Some people may also add something like this to the code:

typedef node_t *node_ptr;

But, I'm not a fan.

As for the other changes, I like making the sizeof in the malloc line to be the size of the object we're allocating. It is "safer" because if you even change the type, you don't need to go hunt out all the malloc's and make sure you change the sizeofs. That's just my personal opinion, though. You could have easily used "sizeof(node_t)". Where you made your mistake (as pointed out by the above poster) was saying "sizeof(node_t *)" (in essence). Which is the size of a pointer not the size of the thing you are pointing to, which is how much space you need.

1 Like