I wrote the following code and it works, but I would like to know if a can be sure that it works all the time on all x86 machines.
#include <stdio.h>
#include <stdlib.h>
typedef struct Base {
int a;
float b;
} Base;
typedef struct Derived1 {
int a; // This two members have the same position as in the Base
float b;
// adding some other members to this struct
int otherMember;
int otherMember2;
} Derived1;
int main()
{
Base *bases[2];
// Filling the array with different structs
bases[0] = (Base*) malloc(sizeof(Base));
bases[1] = (Base*) malloc(sizeof(Derived1));
bases[1]->a = 5;
Derived1 *d1 = (Derived1*) bases[1];
if(d1->a == 5)
printf("SUCCESS\n");
return 0;
}
I know why this example works, but does it work always? Is there padding or similar stuff going on that can prevent this from working, or does the C standard even support this?