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
| #include <stdio.h>
#define type(t) #t
#define new_typed_thing(t) malloc(sizeof (typed_thing) + sizeof(t))
#define typed_data(x,t) *((t*)x->data)
typedef struct {
char * type;
void *data[0];
} typed_thing;
int main() {
int i;
typed_thing *tab[3];
tab[0] = new_typed_thing(int);
tab[0]->type = type(int);
typed_data(tab[0],int) = 8;
tab[1] = new_typed_thing(char);
tab[1]->type = type(char);
typed_data(tab[1],char) = 122;
tab[2] = new_typed_thing(char*);
tab[2]->type = type(char*);
typed_data(tab[2],char*) = "salut";
for (i = 0; i < 3; i++) {
if (tab[i]->type == type(int)) {
printf("%d\n",typed_data(tab[i],int));
}
else if (tab[i]->type == type(char)) {
printf("%d\n",typed_data(tab[i],char));
}
else if (tab[i]->type == type(char*)) {
printf("%s\n",typed_data(tab[i],char*));
}
else {
printf("type non reconnu\n");
}
}
free(tab[0]);
free(tab[1]);
free(tab[2]);
} |