Dereferencing pointer to incomplete type of structure in structure of assignment for the member

Viewed 51

I encountered a problem about pointer and structure.

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

Define two structure, sub term and major term.

typedef struct{
    int sub_id;
    int sub_data;
    struct sub_term *next_term;
}sub_term;

typedef struct{
    char name[10];
    struct sub_term *init_term;
    struct sub_term *current_term;
}major_term;

I want to create a major term that contains sub term.

int main(void){

major_term *Test_1;
Test_1 = (major_term *)malloc(sizeof(major_term));

Test_1->init_term = (sub_term *)malloc(sizeof(sub_term));   
Test_1->current_term = Test_1->init_term;

printf("Sub term 1 id : ");

However, compiler notices me that "[Error] dereferencing pointer to incomplete type" in this line.

scanf("%d",&Test_1->current_term->sub_id);

I am new to C language and not sure the reason. Thank you for your recommend that makes my code better !

printf("Sub term 1 id : ",Test_1->current_term->sub_id);
printf("Sub term 1 data: ");
scanf("%d",&Test_1->current_term->sub_data);
printf("Sub term 1 data : ",Test_1->current_term->sub_data);    

return 0;
}
1 Answers

You need the names for the structures, not just typedefs:

typedef struct sub_term{
//             ^^^^^^^^
    int sub_id;
    int sub_data;
    struct sub_term *next_term;
}sub_term;

typedef struct major_term{
//             ^^^^^^^^^^
    char name[10];
    struct sub_term *init_term;
    struct sub_term *current_term;
}major_term;

Defining type names with typedef like this

typedef struct {} MyType;

does not define the structure with name MyType. Instead, it defines the name MyType as an alias of an unnamed struct.

Structure names and general type names are in two separate namespaces in C, so struct MyType is different from MyType, and they don't interfere with each other.

When you declare a structure without defining it (i.e., providing the content of the structure), the structure is an incomplete type. In your code, you defined pointers to struct sub_term but you didn't define that structure (note again: typedef-ing does not give names to structures - it defines aliases for your unnamed structures), so the compiler complains about "incomlete types".

Related