0

I am trying to forward declare a struct A and define a struct B that contains an array of A. I am getting error stating 'incomplete type not allowed'

This is what I have:

struct A;

struct B
{
// something 
struct A x[10]; // This where I get the error incomplete type not allowed
};

struct A
{
// something
};

What am I doing wrong ?

2 Answers 2

2

As a work around you can declare a pointer to struct A as this

struct B
{
// something 
struct A * x;
};

This is because if you have a line like

struct B b;

the b will have a member x[10]. If you did not fully declare struct A, struct B doesn't know how to allocate 10 struct A elements. In the workaround, if you only declare a pointer, struct B doesn't need to know how to allocate struct A but only need to know how to allocate one pointer.

Sign up to request clarification or add additional context in comments.

Comments

1

An "incomplete type" (MSDN) is a type whose details the compiler doesn't know at a given point in the translation unit. In the declaration of members of struct B, the compiler doesn't know the size of the type (sizeof (struct A)) and therefore doesn't know how much space to leave for it. Another reason for not allowing struct members of incomplete type is that if they could, this would have allowed "circular composition" where struct A contains members of type struct B and vice versa. I don't see how the size of the result of such a circular composition could even be defined.

Workarounds:

  • To include struct A by value in struct B, complete the type first. Move the declaration of members of struct A above that of struct B.
  • A struct is allowed to include pointers to incomplete types as members. In struct B, include an array of pointers (struct A *x[10];) Then populate it with objects of type struct A allocated separately, possibly through some factory that calls malloc(sizeof(struct A)), fills out its members, and returns the pointer. You're then responsible for freeing the memory used by these instances.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.