最好将简单成员作为直接值,并只分配数组。使用额外的两个指针只会减慢访问速度,没有任何好处。
如果你使用的是C99或C11,还有另一个选择是使用灵活数组成员(FAM)。
你可以使用以下表示法来定义结构:
typedef struct my_structure_s
{
int bounds[2];
int num_values;
int values[];
} my_structure_t;
您需要一次性分配足够的内存空间,包括结构体和N个元素数组 values
,可以使用以下代码:
my_structure_t *np = malloc(sizeof(*np) + N * sizeof(np->values[0]));
这意味着你只需要释放一个内存块即可。如果搜索,可以找到“struct hack”的参考资料。这种表示法实际上是“struct hack”的标准形式。
在评论中,讨论继续:
这是一种有趣的方法;然而,我不能保证我会有C99。
如果需要的话,您可以使用代码的 'struct hack' 版本,它看起来像:
typedef struct my_structure_s
{
int bounds[2];
int num_values;
int values[1];
} my_structure_t;
其余代码保持不变。这种方法使用的内存略多一些(比FAM解决方案多4-8个字节),并不严格符合标准,但在C99标准之前广泛使用,因此编译器不太可能使这样的代码无效。
Okay, but how about:
typedef struct my_structure_s
{
int bounds[2];
int num_values;
int values[MAX_SIZE];
} my_structure_t;
And then: my_structure_t *the_structure = malloc(sizeof(my_structure_t));
This will also give me a fixed block size on the heap right? (Except here, my block size will be bigger than it needs to be, in some instances, because I won't always get to MAX_SIZE).
如果平均浪费空间不太多,那么结构体中的固定大小数组仍然更简单。此外,这意味着如果MAX_SIZE不是太大,则可以在堆栈或堆上分配,而FAM方法则需要动态(堆)分配。问题是浪费的空间是否足够成为问题,以及如果MAX_SIZE实际上不够大,该怎么办。否则,这是最简单的方法;我只是假设您已经排除了它。
请注意,建议的每个解决方案都避免了选项2中建议的指向bounds和num_values的指针。