I am writing a C program in which I define two types:
typedef struct {
uint8_t array[32];
...
} A;
typedef struct {
uint8_t array[32];
...
} B;
Now I would like to build a data structure that is capable of managing both types without having to write one for type A and one for type B, assuming that both of them have uint8_t [32] as their first member.
I read how you can implement some kind of polymorphism in C, and I also read here that the order of the structure members is guaranteed to be stored by the compiler, as written by the programmer.
I came up with the following idea: what if I define the following structure:
typedef struct {
uint8_t array[32];
} Element;
and define a data structure that only applies to data of type Element? It would be safe to do something like:
void f(Element * e){
int i;
for(i = 0; i < 32; i++) do_something(e->array[i]);
}
...
A a;
B b;
...
f(((Element *)&a));
...
f(((Element *)&b));
At first glance it looks unclean, but I was wondering if there were any guarantees that it would not break?