在 C 中,是否应该允许我使用指向不完整类型数组的指针?
In C, should I be allowed to use pointers to arrays of incomplete types?
IAR 嵌入式 C 编译器对此很满意,我认为它是正确的 C 代码:
struct incomplete;
typedef struct incomplete (*why_not)[2];
struct incomplete {struct incomplete *known_to_work;} array[2];
why_not ok = &array;
然而,gcc 和 clang 在 why_not
的定义上卡住了:
incomplete.c:2:29: error: array type has incomplete element type ‘struct incomplete’
typedef struct incomplete (*why_not)[2];
^
从技术上讲,没有理由拒绝 "pointer to array of incomplete" 类型的定义。毕竟,只有在取消引用此类变量或执行某些指针运算时才需要结构定义。
我很想尽可能隐藏结构定义。
C 标准对此有何规定?
下面的语句
typedef struct incomplete (*why_not)[2];
是指向两个struct incomplete
的数组的指针。编译器还不知道 struct incomplete
的大小,因为它还没有定义。
然而,以下将起作用:
typedef struct incomplete *why_not[2];
即:指向 struct incomplete
的指针数组。编译器确实知道指向不完整类型的指针的大小(即:它只是存储地址所需的大小)。
编辑:
在任何一种情况下,编译器都不需要知道 struct incomplete
的大小(只要没有指针运算发生),因为两个声明都只是声明指针。
该代码使用了数组声明符,其中元素类型不完整。根据 6.7.6.2/1 Array declarators:
,这是 ISO C 中的约束违规
Constraints
In addition to optional type qualifiers and the keyword static, the [
and ]
may delimit an expression or *
. 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.
IAR 嵌入式 C 编译器对此很满意,我认为它是正确的 C 代码:
struct incomplete;
typedef struct incomplete (*why_not)[2];
struct incomplete {struct incomplete *known_to_work;} array[2];
why_not ok = &array;
然而,gcc 和 clang 在 why_not
的定义上卡住了:
incomplete.c:2:29: error: array type has incomplete element type ‘struct incomplete’
typedef struct incomplete (*why_not)[2];
^
从技术上讲,没有理由拒绝 "pointer to array of incomplete" 类型的定义。毕竟,只有在取消引用此类变量或执行某些指针运算时才需要结构定义。
我很想尽可能隐藏结构定义。
C 标准对此有何规定?
下面的语句
typedef struct incomplete (*why_not)[2];
是指向两个struct incomplete
的数组的指针。编译器还不知道 struct incomplete
的大小,因为它还没有定义。
然而,以下将起作用:
typedef struct incomplete *why_not[2];
即:指向 struct incomplete
的指针数组。编译器确实知道指向不完整类型的指针的大小(即:它只是存储地址所需的大小)。
编辑:
在任何一种情况下,编译器都不需要知道 struct incomplete
的大小(只要没有指针运算发生),因为两个声明都只是声明指针。
该代码使用了数组声明符,其中元素类型不完整。根据 6.7.6.2/1 Array declarators:
,这是 ISO C 中的约束违规Constraints
In addition to optional type qualifiers and the keyword static, the
[
and]
may delimit an expression or*
. 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.