Q: Having trouble with function pointers and array I am currently using Visual Studios for class and needless to say I am having difficulty understanding pointers. I have created a program but does not seem to work right for me. I keep getting an assertion error after I click the function type that I want. I get a Debug assertion failed pop up error. Expression: result_pointer != nullptr. It says line 1558 
int function1(int a,int b);
int function2(int a, int b);
int function3(int a, int b);

int(*p[3])(int x, int y);

int main()
{

    int num1, num2;
    int choice = 0;

    p[0] = function1;
    p[1] = function2;
    p[2] = function3;

    printf("Please enter two numbers: ");
    scanf_s("%d", &num1);
    scanf_s("%d", &num2);
    printf("Which would you like to try (1 for Math, 2 for Subtraction, 3 for Multiplication): \n");
    scanf_s("%d", choice);
    int (*i) = &choice;

    while (*i >= 0 && *i < 3) {
        (p[*i])(num1,num2);
    }

puts("Program execution compiled");
}
int function1(int a, int b) 
{
    int total;
    total = a + b;
    return total;

}
int function2(int a, int b) 
{
    int total;
    total = a - b;
    return total;
}
int function3(int a, int b) 
{
    int total;
    total = a * b;
    return total;
}


A: This is why your code fails:
scanf_s("%d", choice);

You forgot to use the address of operator &.
scanf_s("%d", &choice);

Of course there are a number of other quirks with your code.
For example,


*

*Why do you use int (*i) = &choice;? Wouldn't it make more sense just to take the choice and subtract 1? No need to use pointers int i = choice - 1.

*Your loop is going to execute the body of the loop until i is less than zero or greater than 2, which is never if the input entered is correct. Consider choosing another loop condition, or swapping the loop with an if statement.

*You don't ever display the return value of the function. Try something like this printf("%d\n", (p[i])(num1,num2) (assuming you've fixed the i is a pointer thing)

