简体   繁体   English

在C中,我应该被允许使用指向不完整类型数组的指针吗?

[英]In C, should I be allowed to use pointers to arrays of incomplete types?

The IAR Embedded C compiler is happy with this, and I assumed it was correct C code: IAR Embedded C编译器对此很满意,我认为它是正确的C代码:

struct incomplete;
typedef struct incomplete (*why_not)[2];
struct incomplete {struct incomplete *known_to_work;} array[2];
why_not ok = &array;

However, gcc and clang choke on the definition of why_not : 但是,gcc和clang对于why_not的定义why_not

incomplete.c:2:29: error: array type has incomplete element type ‘struct incomplete’
 typedef struct incomplete (*why_not)[2];
                             ^

Technically, there is no reason to reject a definition of a "pointer to array of incomplete" type. 从技术上讲,没有理由拒绝“指向不完整数组的指针”的定义。 After all, the structure definition is needed only where such a variable is dereferenced, or some pointer arithmetics is performed. 毕竟,只有在取消引用这样的变量或执行某些指针算术时才需要结构定义。

I'm eager to hide structure definitions where possible. 我渴望在可能的情况下隐藏结构定义。

What does the C standard say about this? C标准对此有何看法?

The code uses an array declarator where the element type is incomplete. 代码使用数组声明符,其中元素类型不完整。 This a constraint violation in ISO C, according to 6.7.6.2/1 Array declarators : 根据6.7.6.2/1 数组声明符,这是ISO C中的约束违规:

Constraints 约束

In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or * . 除了可选的类型限定符和关键字static之外, []可以分隔表达式或* If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. 如果它们分隔表达式(指定数组的大小),则表达式应具有整数类型。 If the expression is a constant expression, it shall have a value greater than zero. 如果表达式是常量表达式,则其值应大于零。 The element type shall not be an incomplete or function type. 元素类型不应是不完整或函数类型。

The following statement 以下声明

typedef struct incomplete (*why_not)[2];

is a pointer to an array of two struct incomplete . 是一个指向两个struct incomplete的数组的指针。 The compiler does not know the size of struct incomplete yet, since it is not yet defined. 编译器还不知道struct incomplete的大小是否已struct incomplete ,因为它尚未定义。

The following will however work: 但是,以下内容将起作用:

typedef struct incomplete *why_not[2];

ie: an array of pointers to struct incomplete . ie: struct incomplete的指针数组。 The compiler does know the size of a pointer to an incomplete type (ie: it is just the size needed to store an address). 编译器确实知道指向不完整类型的指针的大小(即:它只是存储地址所需的大小)。


Edit: 编辑:

The compiler does not need to know the size of struct incomplete in either case (as long as no pointer arithmetic is taking place), since both declarations are just declaring pointers. 在任何一种情况下,编译器都不需要知道struct incomplete的大小(只要没有指针算术发生),因为两个声明都只是声明指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM