Resolving the "dereferencing pointer to incomplete type" error

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.");
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved