您不能拥有具有灵活数组成员的结构数组。
这是这个问题的 TL;DR 。仔细想想,这完全有道理。
但是,可以模拟一个具有灵活数组成员的结构数组 - 我们称它们为swfam -固定大小,如下所示:
#include <assert.h>
#include <stdlib.h>
typedef struct {
int foo;
float bar[];
} swfam_t; // struct with FAM
typedef struct { // this one also has a FAM but we could have used a char array instead
size_t size, // element count in substruct
count; // element count in this struct
char data[];
} swfam_array_t;
#define sizeof_swfam(size) (sizeof(swfam_t) + (size_t)(size) * sizeof(float))
swfam_array_t *swfam_array_alloc(size_t size, size_t count) {
swfam_array_t *a = malloc(sizeof(swfam_array_t) + count * sizeof_swfam(size));
if (a) {
a->size = size;
a->count = count;
}
return a;
}
size_t swfam_array_index(swfam_array_t *a, size_t index) {
assert(index < a->count && "index out of bounds");
return index * sizeof_swfam(a->size);
}
swfam_t *swfam_array_at(swfam_array_t *a, size_t index) {
return (swfam_t *)&a->data[swfam_array_index(a, index)];
}
int main(int argc, char *argv[]) {
swfam_array_t *a = swfam_array_alloc(100, 1000);
assert(a && "allocation failed");
swfam_t *s = swfam_array_at(a, 42);
s->foo = -18; // do random stuff..
for (int i = 0; i < 1000; ++i)
s->bar[i] = (i * 3.141592f) / s->foo;
free(a);
return 0;
}
这个技巧有效 C99 / C11 吗?我是否潜伏于未定义的行为?