Home > Software engineering >  Dictionary in C with functions as values
Dictionary in C with functions as values

Time:10-20

I'm making a game in alegro for a Uni project and wanted to use a dictinary or something like a hashmap to minimize the amount of ifs per action in the code and be able to implement some vary basic skin mechanics. Problem is I don't have any ideia how to implement such a thing. I've been using C for quite some time now, so I'm very confortable with dynamic memory allocation and controlling complex programs. Do you guys have any tips on how I can accomplish this?

The idea is to build a dictionary in which the keys are strings and the values are functions, so I can operate over the functions via indexing

CodePudding user response:

As Barmar mentioned, you could utilize a hash table for mapping char* to function pointers if your functions have the same return types. If strings aren't strictly required in your case, you can get by with a simplified version of a hash table with macros.

#define A 0
#define B 1
#define C 2

void a() {}
void b() {}
void c() {}

void (*funcs[3])() = {
    [A] = &a,
    [B] = &b,
    [C] = &c,
};

int main(int argc, char *argv[]) {
  (*funcs[B])();
  return 0;
}

CodePudding user response:

If you're using a POSIX system you can use the standard library functions hcreate/hsearch/hdestroy to manage a single hash table with strings as keys. On a GNU system (any that uses glibc) you can use the _r versions of those functions to manage multiple hash tables.

The hash tables are pretty minimal -- the ENTRY type is hard-coded (in <search.h>) to be

       typedef struct entry {
           char *key;
           void *data;
       } ENTRY;

See the hsearch(3) man page for more details.

  • Related