Search code examples
cfunction-pointersgetopt

Function Pointers not working in getopt


I have some code which tests the robustness of a variety of PRNGs, and I want to choose which PRNG is being tested using options.

I have a function pointer type: typedef double (*voidPRNG_ptr)(void);

I have a testing function: test_results* investigator_alloc(int N, voidPRNG_ptr RNGp) Where test_results is a typedef'ed struct.

I have PRNG functions: double box_muller(void), double rejection(void), double RNG(void), etc...

The following code in main works FINE:

int main(int argc, char** argv){ 
    int N = atoi(argv[1]);
    voidPRNG_ptr PRNGp = &box_muller; 

    test_results* results = investigator_alloc(N, PRNGp); 

    return 0;
    }

The box_muller function is used as the RNG, and data is as expected.

This also WORKS FINE:

int main(int argc, char** argv){ 
    int N = atoi(argv[1]);
    voidPRNG_ptr PRNGp = &box_muller; 

    PRNGp = &rejection; 

    test_results* results = investigator_alloc(N, PRNGp); 

    return 0;
    }

The rejection method is used as the RNG, as expected.

However, this DOESN'T work:

int main(int argc, char **argv){
   int opt;
   int atest = 0;
   voidPRNG_ptr PRNGp = &RNG;   //set default

   while((opt = getopt(argc, argv, "abur")) != -1){ 
        if(opt == 'a') {
            PRNGp = &normal_approx; 
            atest = 1;
        }           
        else if(opt == 'b') PRNGp = &box_muller; 
        else if(opt == 'u') PRNGp = &RNG; 
        else if(opt == 'r') PRNGp = &rejection; 
   }

    printf("\n %d\n",atest); 


    int N = atoi(argv[1]);
    //PRNGp = &rejection;
    //PRNGp = &normal_approx;
    //PRNGp = &box_muller; 

    test_results *results = investigator_alloc(N,PRNGp);
    return 0; 
}

I know that getopt is working as atest is set to the right value depending on the option selected. But there must be something wrong with the function pointer as the data is blank.

Any ideas? Thanks!


Solution

  • The issue is that you're applying atoi() to the first command-line argument, which is the option that tells your program which RNG to use. Since argv[1] is not numeric, you end up with N=0 and no data.

    Change argv[1] to argv[optind] (see Using the getopt function).