我正在传递一个指向结构的指针,前 8 个成员大小相同,我可以通过索引访问它们吗?
typedef struct example{
uint64_t one;
uint64_t two;
uint64_t three;
uint64_t four;
uint64_t five;
//etc...
uint8_t ninth;
} example_t;
void example_method(example_t *ptr)
{
//can I do this?
&ptr[2] // which would be equal to the uint64_t third?
}
最佳答案
您不能通过索引可靠地获取结构成员的原因是结构可能在成员之间以及在最后一个成员之后包含任意填充。根据 C11,N1570 §6.7.2.1/p15 结构和 union 说明符:
There may be unnamed padding within a structure object, but not at its beginning.
您可以做的是重新定义您的结构以包含数组成员(或者可能是 flexible array member )。
关于c - 通过索引访问结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36137050/