2015-02-07 78 views
0

我试图向前声明一个struct A和定义包含“不准不完全型”阵列前进的另一个结构

这是A. 我得到错误,指出数组的结构乙声明结构我有什么:

struct A; 

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

struct A 
{ 
// something 
}; 

我在做什么错?

回答

2

这样的工作,你可以左右一个声明指向struct A作为该

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

这是因为如果你有一个像

struct B b; 

线的b将有一个成员x[10]。如果你没有完全声明struct A,那么struct B不知道如何分配10个struct A元素。在变通方法中,如果只声明一个指针,则struct B不需要知道如何分配struct A,但只需知道如何分配一个指针。

1

“不完整类型”(MSDN)是一种类型,其编译器在翻译单元的给定点处不知道的细节。在struct B的成员声明中,编译器不知道类型的大小(sizeof (struct A)),因此不知道要为它留出多少空间。不允许struct成员的不完整类型的另一个原因是,如果他们可以,这将允许“圆形成分”,其中struct A包含struct B类型的成员,反之亦然。我不明白这样一个循环组合的结果的大小甚至可以被定义。

解决方法:

  • struct B包括struct A由值,首先完成的类型。将struct A的成员声明移至struct B以上。
  • A struct被允许包含指向不完整类型的指针作为成员。在struct B中包含一个指针数组(struct A *x[10];)然后用单独分配的struct A类型的对象填充它,可能通过调用malloc(sizeof(struct A))的某个工厂填充其成员并返回指针。然后,您负责释放这些实例使用的内存。