Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Related Tags

dereferencing
pointer
incomplete
type
solution

# Resolving the "dereferencing pointer to incomplete type" error

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

The “dereferencing pointer to incomplete type” error commonly occurs in C when one tries to dereference a type (usually a struct) that is:

• not declared at all.
• declared, but not defined.

The error in the first bullet point occurs because C cannot find the struct that is being dereferenced. The reason for this could be that the struct may not have been declared, or that the user made a typographical error in the struct’s name.

The following is an example of the error in the second bullet point​:

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

struct {
int age;
float weight;
} person;

int main()
{
// Declare a pointer to the struct and allocate memory
struct person *ptr;
ptr = (struct person*)malloc(sizeof(struct person));
// Fill in the struct with data.
ptr->age = 10;
ptr->weight = 55.5;
}

Run the code above and note the two errors – both of them refer to the incomplete type struct person. Therefore, the fault lies in the declaration of the struct.

Lines 4-7 have defined a nameless struct type and a variable (person) of that type. Since the compiler has not associated a name with the struct, it throws an error whenever person is referenced.

The solution is to declare the struct with its name right after the struct keyword:

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

struct person {
int age;
float weight;
};

int main()
{
struct person *ptr;
ptr = (struct person*)malloc(sizeof(struct person));
ptr->age = 10;
ptr->weight = 55.5;
printf("%s", "Successful.");
}

RELATED TAGS

dereferencing
pointer
incomplete
type
solution