きったんの頭

/*
 * Sample code for struct and (void *).
 * https://mind.kittttttan.info/c/struct
 */
#include <stdio.h>
#include <string.h>

enum {
    INTEGER 0
    ULONG   1
    STRING  2
};

typedef struct _Test {
    int d;
    unsigned long lu;
    char s[8];
} Test;

typedef struct _DB {
    int no;
    char *id;
    int type;
    void *data;
} DB;

Test t = {7, 7777777, "Nana"};
DB d[3];

void printTest() {
    printf("%-3s %-7s %-7s\n", "d", "lu", "s");
    printf("%3d %7lu %7s\n", t.d, t.lu, t.s);
}

void setDB(int no, char *id, int type, void *data) {
    d[no].no = no;
    d[no].id = id;
    d[no].type = type;
    d[no].data = data;
}

void createDB() {
    int i = 0;
    setDB(i++, "d", INTEGER, &t.d);
    setDB(i++, "lu", ULONG, &t.lu);
    setDB(i++, "s", STRING, t.s);
}

void printDB() {
    int i;
    for (i = 0; i < 3; ++i) {
        switch(d[i].type) {
        case INTEGER:
            printf("%3d %2s %7d\n", i, d[i].id, *(int*)d[i].data);
            break;
        case ULONG:
            printf("%3d %2s %7lu\n", i, d[i].id, *(unsigned long*)d[i].data);
            break;
        case STRING:
            printf("%3d %2s %7s\n", i, d[i].id, (char*)d[i].data);
            break;
        default:
            printf("%3d %2s Unknown\n", i, d[i].id);
            break;
        }
    }
}

void setTest(int no, void *data) {
    switch(d[no].type) {
    case INTEGER:
        *(int*)d[no].data = *(int*)data;
        break;
    case ULONG:
        *(unsigned long*)d[no].data = *(unsigned long*)data;
        break;
    case STRING:
        strncpy(d[no].data, data, 7);
        break;
    default:
        fprintf(stderr, "Error\n");
        break;
    }
}

int main() {
    int i = 3;
    char *s = "Mizuki";
    createDB();

    puts("init");
    printTest();

    printf("\nset %s to %d\n", d[0].id, i);
    setTest(0, &i);
    printTest();

    printf("\nset %s to %s\n", d[2].id, s);
    setTest(2, s);
    printTest();

    return 0;
}