ftl25 0 Junior Poster in Training

I have a look up table as follows:

// A structure to hold all the commands and function pointers
typedef struct
{
    char functionName[256];// The function name is used to refer to the function pointer
    int (_stdcall *myfunction)(char *, char *);	// This defines the function pointer
} LOOKUP_TABLE;

// This lookup table holds all TSL1 commands and their related functions
static const LOOKUP_TABLE lookUpTable[] = 
{ 
    {"ReadMemory8", pTSL1_Commands->DIAG_ReadMem8},
    {"ReadMemory16", pTSL1_Commands->DIAG_ReadMem16},
    {"ReadMemory32", pTSL1_Commands->DIAG_ReadMem32},
    {"ReadMemory64", pTSL1_Commands->DIAG_ReadMem64},
    {NULL, NULL} 
};

I have a variable, sCmdInt[0] which holds a string to be compared to the elements in the lookup table.
Can anyone help with how to loop around the lookup table to find a match for the function? I have tried the following:

int n = sizeof(lookUpTable)/sizeof(*lookUpTable);
for (int i = 0; i < n; i++)
{
    if(sCmdInt[0] == lookUpTable->functionName[i])
    {
        (*(lookUpTable[i].myfunction(sCmdInt[0], returnData)));
    }
}

My function, when called, also takes sCmdInt[0] and returnData as parameters.
Any help appreciated.

Dani AI

Generated

Three small fixes will make this work:

  • Compare strings with strcmp, not ==. == compares pointers, not the characters they point to. See strcmp.
  • Index the table correctly: use lookUpTable[i].functionName (not lookUpTable->functionName[i]).
  • Call the function pointer directly; you do not need to dereference the result of the call.

Example using your sentinel entry to stop the loop:

for (size_t i = 0; lookUpTable[i].myfunction != NULL; ++i) {
    if (strcmp(sCmdInt[0], lookUpTable[i].functionName) == 0) {
        int rc = lookUpTable[i].myfunction(sCmdInt[0], returnData);
        // handle rc if needed
        break; // found the match; stop searching
    }
}

Notes and gotchas:

  • If you want case-insensitive matches, use _stricmp on Windows or strcasecmp on POSIX.
  • Your function pointer type should use the MSVC spelling __stdcall (two underscores), not _stdcall: see __stdcall.
  • The final {NULL, NULL} sentinel works because it zero-initializes the char array and the pointer. Checking myfunction != NULL is a clean stop condition.
  • If pTSL1_Commands is set at runtime, avoid initializing a static const table with pTSL1_Commands->... at file scope (that is not a constant expression). In that case, either make the table non-const and fill the myfunction fields after pTSL1_Commands is initialized, or build the table dynamically before lookup.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.