How to pass a function pointer by parameter?

Asked

Viewed 324 times

1

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

I can’t make comparisons of strings, then I must 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;
}

This way the algorithm compiles but does not execute.

  • I can compile, but not even enter the cycle for

  • argc is not zero-based? In that case the for has to start at i = 0.

  • I already started in i = 1 because in argv[0] you have the file directory.

  • If the exercise asks for pass the name of a function, I find it hard to escape making comparisons of strings at some point. It gives an investigation into this requirement.

  • @Fightforwhat Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on all the posts on the site as well. Did any help you more? You need something to be improved?

1 answer

1

I couldn’t even compile.

(func)argv[i]

Doesn’t magically transform a string on a pointer to function. It is impossible to make this direct transformation.

The best you can achieve is to assemble a table of lookup with the function names and their respective pointers. Somehow there will be a comparison of strings. You can even use a table hash for this but still there will be comparison.

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

In languages that have metadata is simpler. But in the background there will be comparison even if you are not seeing it. It is possible to use some C library to achieve this if you load an external module. In Dlls there is some metadata. But a comparison will occur, you just won’t see it.

  • My data structure teacher he even created the first operating system in Rio Grande do Sul.

  • I’m not defending the old man but there are things he’s pretty clueless...

  • 1

    There is another possibility. You don’t understand the requirement. But I believe more in being some tricky proposition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.