是否可以创建一个已声明但未定义类型的数组?这就是我想做的:
typedef struct _indiv indiv;
typedef indiv pop[];
并让其他人通过在另一个 .c 或 .h 文件中定义 struct _indiv(然后将所有内容链接在一起)来决定个人的成员实际上是什么。
(就语义而言,indiv 是个体,pop 是个体的群体。)
但是编译器提示:
error: array type has incomplete element type
我可以将第二个 typedef 替换为
typedef indiv * pop;
并通过访问像 p[i]
这样的元素(p 类型为 pop)来像数组一样使用 pop,但如果我这样做,编译器会提示
error: invalid use of undefined type ‘struct _indiv’
error: dereferencing pointer to incomplete type
我想由于 typedef struct _indiv indiv
只是一个声明,编译器在编译时(链接之前)不知道该结构需要多少空间并且它不喜欢它,因此禁止做我正在尝试的事情。但我想知道为什么以及是否有可能的方法来实现我想要的。
谢谢
最佳答案
如果您希望此源文件操作 indiv
类型的项目,那么您有 2 个选择。
1) 声明结构,但不定义它。仅使用指向结构的指针。切勿取消引用它们:
struct _indiv;
typedef struct _indiv indiv;
typedef indiv * pop;
//sizeof(_indiv) is not known, how many bytes should we allocate?
pop p = malloc(N*unknownSize);
//this line will fail because it does not know how many bits to copy.
p[0] = getIndiv();
2)定义完整的结构:
struct _indiv
{
int id;
char* name;
/*...*/
};
typedef struct _indiv indiv;
typedef indiv * pop;
pop p = malloc(N*sizeof(indiv));
//Now this line can work.
p[0] = getIndiv();
定义虚拟“indiv”的建议是一个糟糕的建议:
--- file1.c
struct _indiv
{
char dummy;
};
typedef struct _indiv indiv;
typedef indiv * pop;
pop p = malloc(N*sizeof(indiv)); //this will allocate N bytes.
//This will generate code that copies one byte of data.
p[0] = getIndiv();
---realIndiv.c
typedef struct _indiv
{
int id;
char* name;
/*...*/
} indiv;
indiv getIndiv();
{
indiv i = /* whatever */;
return i; //this will return 8+ bytes.
}
当您执行此操作时,第一个文件将操作与“真实”indiv 结构不同大小的项目,并且您肯定会得到意想不到的行为。
关于c - 尚未定义类型的数组(不完整元素类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5069102/