c - 通过索引访问结构

标签 c pointers indexing struct

我正在传递一个指向结构的指针,前 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/

相关文章:

c - 从 C 到 Swift 的函数回调

c - 在 MSP430 上,当我取消引用空指针时会发生什么?

c - 如何防止字符指针缓冲区溢出?

MySQL 简单但查询速度慢(索引错误?)

c - 如何检查输入是否为C中的字母?

c++ - 在 Unix 中将 json 作为命令行参数传递

c++ - 子串搜索面试题

c - 在 C 中分配指针的不同方法,使用 & 或 *?

indexing - Lua中返回表的索引

javascript - 如何在javascript中获取具有多个子元素的数组元素的索引