How to maintain a mapping between a string and it's index in C?
c
Solution
You can do something like
entries.h
ENTRY(APPLE, "apple"),
ENTRY(MANGO, "mango"),
In your file
#define ENTRY(a,b) b
const char *fruits [] = {
#include "entries.h"
} ;
#undef ENTRY
#define ENTRY(a,b) a
enum fruit_t
{
#include "entries.h"
} ;
Problem
I have an enum Eg. ``` enum { APPLE, MANGO, BANANA } ``` and a corresponding string array ``` char fruits[] = { "apple", "mango", "banana" } ``` I need to retrieve the index of string, given I have the string. So given that the string is apple, I need to get 0 and so on. [ `Enum` is additionally there, might help the solution] Is there an elegant way, to save `[apple,0],[banana,1]` that is short and simple, that I might use as a macro. I don't need lengthy things like a hashtable. Can `Enum` assist in the mapping?