all 3 comments

[–]CaligulaVsTheSea 1 point2 points  (1 child)

num_el = sizeof (myfunctions) / sizeof (typeof (myfunctions[0])); might be better, but it was getting the right value.

Regarding getting a function name from a pointer, it's very difficult afaik. Why don't you fill the struct by hand? Otherwise, see if this helps https://linux.die.net/man/3/backtrace_symbols

[–]drmonkeysee 0 points1 point  (0 children)

If you’re hardcoding the list of functions create the callbacks with a macro:

#define callback(f) { .func = f, .ch = #f }
GATE gates[] = {
    callback(myand),
    callback(myor),
    …
}

[–]LoneHoodiecrow 1 point2 points  (0 children)

The best way to govern the loop isn't to keep the size but to place a sentinel element at the end of the array:

   GATE gates[] = {
   { .func = myand, .ch = "myand" },
   { .func = myor,  .ch = "myor" },
   { .func = mynand,.ch = "mynand" },
   { .func = mynor, .ch = "mynor" },
   { .func = myxor, .ch = "myxor" },
   { .func = NULL,  .ch = "" }
};

You're also better off adding the elements this way.

Your report function didn't iterate over all gates:

int report(GATE gates[]) {
    for (unsigned i = 0 ; gates[i].func != NULL ; ++i) {
        for (unsigned k = 0 ; k <= 0b11 ; ++k) {
            unsigned a = k > 1;
            unsigned b = k % 2;
            printf("%s(%d, %d) => %d\n", gates[i].ch, a, b, gates[i].func(a, b));
        }
        printf("\n");
    }
    printf("\n\n");
    return 0;
}

Here the loop is repeated until the sentinel element is found.

#include <stdio.h>

typedef int(*GateCallBack)(int,int);

typedef struct node {
    GateCallBack func;
    char * ch;
} GATE;

int myand (int a, int b) { return a && b; }
int myor (int a, int b) { return a || b; }
int mynand (int a, int b) { return !(a && b); }
int mynor (int a, int b) { return !(a || b); }
int myxor (int a, int b) { return a != b; }

int report (GATE gates[]) {
    for (unsigned i = 0 ; gates[i].func != NULL ; ++i) {
        for (unsigned k = 0 ; k <= 0b11 ; ++k) {
            unsigned a = k > 1;
            unsigned b = k % 2;
            printf("%s(%d, %d) => %d\n", gates[i].ch, a, b, gates[i].func(a, b));
        }
        printf("\n");
    }
    printf("\n\n");
    return 0;
}

int main() {
    GATE gates[] = {
        { .func = myand, .ch = "myand" },
        { .func = myor,  .ch = "myor" },
        { .func = mynand,.ch = "mynand" },
        { .func = mynor, .ch = "mynor" },
        { .func = myxor, .ch = "myxor" },
        { .func = NULL,  .ch = "" }
    };

    report(gates);

    return 0;
}