I have records
具有灵活的阵列成员
typedef struct record {
unsigned foo;
signed bar;
double number[];
} record;
我有多个records
与相同数量的numbers
这样我就可以将它们排列成数组。我想将它们分配到一个连续的内存空间中。
const unsigned numbers = ...;
const unsigned records = ...;
const size_t record_size = sizeof(record) + numbers*sizeof(double);
record *prec = malloc(records*record_size);
所以现在我知道了record_size
我可以访问它,但最佳实践是什么,如何通过给定的方式正确、安全地做到这一点record
index?
当我将包含的标题分开时我可以做到这一点foo
and bar
and numbers
,但我想保留record
在一起以实现缓存一致性。
由于只有您知道实际的布局,因此 C 编译器无法帮助您。因此,您必须自己进行地址计算。需要进行一些强制转换才能在字节级别进行指针算术:
record * get_record(record *base, size_t numbers, size_t index)
{
return (record *) ((unsigned char *) base +
index * (sizeof *base + numbers * sizeof *base->number));
}
鉴于上述(和你的代码);您可以像这样访问该数组:
record *first = get_record(base, numbers, 0);
first->foo = 4711;
record *second = get_record(base, numbers, 1);
second->foo = 17;
一个明显的缺点是你必须保留numbers
值周围。这可以通过使用显式“基”结构对整个数组进行建模来改进,该结构保存每个元素的大小和基指针。当然,它可以与元素本身共同分配,以将其全部放在一起并减少所涉及指针的距离。
Also, 请不要转换返回值malloc() in C https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)