Trusted answers to developer questions

Resolving the "dereferencing pointer to incomplete type" error

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?