Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a struct by index

I'm being passed a pointer to a struct, and the first 8 members are the same size, can I access them by index?

 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?
}
like image 235
Anon Avatar asked Mar 22 '26 07:03

Anon


1 Answers

The reason why you cannot reliably take an struct member by index is that struct may contain arbitrary padding between members, as well as after last member. According to C11, N1570 §6.7.2.1/p15 Structure and union specifiers:

There may be unnamed padding within a structure object, but not at its beginning.

What you can do about it is to redefine your struct to contain array member (or possibly flexible array member).

like image 158
Grzegorz Szpetkowski Avatar answered Mar 23 '26 20:03

Grzegorz Szpetkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!