C 标准不支持这一点。在实践中,您可以计算运行时结构大小和元素位置:
#include <stddef.h>
typedef struct Unknown bar_t;
struct foo_t
{
bar_t *bar;
float baz[];
};
/* Calculate the size required for an array of struct foo_t objects in which
each flexible array member has NElements elements.
*/
size_t SizeOfFoo(size_t NElements)
{
/* Create an unused pointer to provide type information, notably the size
of the member type of the flexible array.
*/
struct foo_t *p;
/* Calculate the size of a struct foo_t plus NElements elements of baz,
without padding after the array.
*/
size_t s = offsetof(struct foo_t, baz) + NElements * sizeof p->baz[0];
// Calculate the size with padding.
s = ((s-1) / _Alignof(struct foo_t) + 1) * _Alignof(struct foo_t);
return s;
}
/* Calculate the address of the element with index Index in an “array” built
of struct foo_t objects in which each flexible array member has NElements
elements.
*/
struct foo_t *SubscriptFoo(void *Base, size_t NElements, ptrdiff_t Index)
{
return (struct foo_t *) ((char *) Base + Index * SizeOfFoo(NElements));
}
这可能存在一些语言律师问题,但我不希望它们影响实际的编译器。