The best way is probably type punning over union
. It allows you to use the same memory area with different variable representations, for example by giving each struct member individual names, while at the same time remaining able to loop through them.
#include <stdio.h>
typedef union {
struct // anonymous struct, requires standard C compiler
{
int a;
int b;
int c;
};
int array[3];
} Example;
int main (void)
{
Example ex = { .a=1, .b=2, .c=3 };
for(size_t i=0; i<3; i++)
{
printf("%d\n", ex.array[i]);
}
}
If you can't change the struct definition, then the second best is some pointer arithmetic through a character type. This takes much more care though, so that you don't end up writing code with poorly-defined behavior - you need to be aware of things like alignment and strict aliasing. Character types are preferred to work with in case the struct turns more complex with different types of members, because character types are safe from aliasing issues.
Assuming uint8_t
is a character type, then:
#include <stdio.h>
#include <stdint.h>
typedef union {
struct
{
int a;
int b;
int c;
};
} Example;
int main (void)
{
Example ex = { .a=1, .b=2, .c=3 };
uint8_t* begin = (uint8_t*)&ex;
uint8_t* end = begin + sizeof ex;
for(uint8_t* i=begin; i!=end; i+=sizeof(int))
{
printf("%d\n", *(int*)i);
}
}