1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <stdio.h>
typedef union {
int a ;
int b ;
} test_union ;
typedef struct {
int a ;
int b ;
} test_struct ;
int main(int argc, char* argv[]) {
test_union tu ;
test_struct ts ;
printf("Sizeof int\t\t\t: %d bytes\n",sizeof(int));
printf("Sizeof union\t\t\t: %d bytes\n",sizeof(test_union));
printf("Sizeof struct\t\t\t: %d bytes\n",sizeof(test_struct));
printf("Adress of union\t\t\t: 0x%08x\n",&(tu));
printf("Adress of 1st union field\t: 0x%08x (offset from union : %d)\n",&(tu.a),((char*)&(tu.a))-((char*)&(tu)));
printf("Adress of 2nd union field\t: 0x%08x (offset from union : %d)\n",&(tu.b),((char*)&(tu.b))-((char*)&(tu)));
printf("Adress of struct\t\t: 0x%08x\n",&(ts));
printf("Adress of 1st struct field\t: 0x%08x (offset from struct : %d)\n",&(ts.a),((char*)&(ts.a))-((char*)&(ts)));
printf("Adress of 2nd struct field\t: 0x%08x (offset from struct : %d)\n",&(ts.b),((char*)&(ts.b))-((char*)&(ts)));
printf("\n\n");
printf("Set 0 into all union / struct fields...\n");
tu.a = 0 ;
tu.b = 0 ;
ts.a = 0 ;
ts.b = 0 ;
printf("\tUnion values\t: a=%d\tb=%d\n",tu.a,tu.b);
printf("\tStruct values\t: a=%d\tb=%d\n",ts.a,ts.b);
tu.a = 10 ;
printf("Set 10 into union field a...\n");
ts.a = 20 ;
printf("Set 20 into struct field a...\n");
printf("\tUnion values\t: a=%d\tb=%d\n",tu.a,tu.b);
printf("\tStruct values\t: a=%d\tb=%d\n",ts.a,ts.b);
tu.b = 30 ;
printf("Set 30 into union field b...\n");
ts.b = 40 ;
printf("Set 40 into struct field b...\n");
printf("\tUnion values\t: a=%d\tb=%d\n",tu.a,tu.b);
printf("\tStruct values\t: a=%d\tb=%d\n",ts.a,ts.b);
return 0;
} |
Partager