指向C中的前向声明结构数组的指针 [英] A pointer to array of forward declared structures in C

查看:90
本文介绍了指向C中的前向声明结构数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C语言中的前向声明有疑问.

I have a question about forward declarations in C.

代码

Code

typedef struct yhash_s t_yhash;// forward declaration
struct yhash_s {
    size_t  size_h; 
    t_yhash (*yhash)[];// pointer to array of structures
};

使用gcc编译代码后,它会抱怨:

Once the code is compiled with gcc, it complains:

错误:数组类型的元素类型为't_yhash'{aka'struct yhash_s'}

我确实了解到[c0]尚不知道,并且无法计算数组的大小,但是我问的是指向未知大小的数组的指针,这应该是完全可解决的恕我直言.

I do understand that t_yhash is not know (yet) and size of array can't be computed, but I am asking about pointer to an array of unknown yet size, which should be perfectly resolvable IMHO.

如何解决该前向声明和结构本身?

How do I fix that forward declaration and struct itself?

推荐答案

问题在于数组声明符的元素类型可能不具有不完整的类型(C11 6.7.6.2/1).并且t_yash(即struct yhash_s)直到结构定义的右括号才完成.

The trouble is that array declarators may not have an incomplete type as the element type (C11 6.7.6.2/1). And t_yash (i.e. struct yhash_s) is not complete until the closing brace of the struct definition.

此规则还负责另一条琐事; (在结构定义完成之前)具有合法性:

This rule is also responsible for another piece of trivia; it's legal to have (before the struct definition is complete):

void func( t_yhash *a );

但不合法:

void func( t_yhash a[] );

即使对于不完整的元素类型规则,调整规则也可以正常工作.

even though the adjustment rule would work just fine if not for the incomplete element type rule.

通过改进此规则以允许某些情况(例如函数原型),可能会稍微改善语言设计,但这显然不是语言设计委员会提出的.

Probably the language design could be improved slightly by refining this rule to allow some cases like the function prototype, but it clearly wasn't something that arose with the language design committee.

但是,即使没有此规则,您的用例也可能会遇到另一个问题.指针的大小可能未知. 指向结构X的数组的指针"与指向结构Y的数组的指针"具有不同的大小是合法的(尽管在实践中不太可能).有一个规则,所有指向struct的指针必须具有相同的大小,但是没有这样的规则指向数组的指针.

But even without this rule, your use case might have another problem; the size of the pointer might not be known. It would be legal (although unlikely in practice) for "pointer to array of struct X" to have a different size than "pointer to array of struct Y". There is a rule that all pointers to struct must have the same size, but no such rule for pointers to array.

这篇关于指向C中的前向声明结构数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆