How to pass a function pointer per parameter?

1

I need to be passed by argv[] , in the main function, the name of a function that will be called by it.

I can not make comparisons of strings , so I should make the call with variables.

Here is my code:

typedef void (*func)(void);
void A (void){ printf("*funcao A*\n"); }
void B (void){ printf("*funcao B*\n"); }
void fun(func fc){ 
    fc(); 
}

int main(int argc, char *argv[]){
    int i;
    for(i = 1; i < argc; i++){ 
        fun(argv[i]);   
    }
    system("PAUSE");
    return 0;
}

In this way the algorithm compiles but does not execute.

    
asked by anonymous 25.11.2014 / 03:44

1 answer

1

I could not even compile.

(func)argv[i]

Magically does not transform a string into a pointer to function. It is impossible to make this transformation directly.

The best you can do is to set up a lookup table with the names of the functions and their respective pointers. Somehow there will be a comparison of strings . You can even use a hash table for this but even then there will be a comparison.

If you have understood correctly the requirement who created this requirement or do not know how a computer works or is thinking of some tricky trick.

In languages that have metadata, it's simpler. But deep down there will be comparison even if you are not seeing it. You can use some C library to achieve this if you load an external module. There is some metadata in DLLs. But a comparison will occur, you just will not see it.

    
25.11.2014 / 08:18