Iterating over same type struct members in C

Most of the attempts using a union with an array are prone to failure. They stand a decent chance of working as long as you only use int’s, but for other, especially smaller, types, they’re likely to fail fairly frequently because the compiler can (and especially with smaller types often will) add padding between members of a struct, but is not allowed to do so with elements of an array).

C does, however, have an offsetof() macro that you can use. It yields the offset of an item in a struct, so you can create an array of offsets, then (with a bit of care in casting) you can add that offset to the address of the struct to get the address of the member. The care in casting is because the offset is in bytes, so you need to cast the address of the struct to char *, then add the offset, then cast the result to the type of the member (int in your case).

Leave a Comment