0

We just learnt in school about function pointers in C and i wanted to try them out in a test program. The idea is obviously pretty simple. However, when i try to use result = (*funcPtr)(); i get an STATUS_ACCESS_VIOLATION exception but i can't tell what i did wrong. Any ideas on what i'm missing?

#include <stdio.h>

int fun1();
int fun2();

int (*funcPtr)(void);

int fun1() {
  return 1;
}

int fun2() {
  return 2;
}

int main(void) {
  int input,result = 0;
  scanf("%d",input);
  if(input == 1) {
    funcPtr = &fun1;
  } else if(input == 2) {
    funcPtr = &fun2;
  }
  result = (*funcPtr)();
  printf("%d\n",result);
}
5
  • 2
    It's problem with scanf (scanf("%d",input);) not with function pointer. You are missing&. Commented Nov 5, 2018 at 16:06
  • 3
    Don't forget to handle the case where input is neither 1 nor 2. Commented Nov 5, 2018 at 16:06
  • You might want to learn how to debug your programs. Especially how to use a debugger to catch crashes as they happen to locate where in your code the problem is. Commented Nov 5, 2018 at 16:07
  • 1
    Hint: scanf() Commented Nov 5, 2018 at 16:07
  • You should really include (void) in place of () in the function declarations and definitions. There is a difference. Commented Nov 5, 2018 at 16:08

1 Answer 1

4

You forgot a & before input in the scanf. Therefore scanf writes not to the address of the input variable, but to its value (and the variable is uninitialized a this point).

Change that line to:

scanf("%d", &input);

to pass a pointer to input to scanf and not the value of input.

And as already pointed out by other users, do not forget to handle inputs other than 1 and 2. Otherwise you will call your uninitialized funcPtr variable, which most likly results in a Segmentation fault.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, you and the others who commented pointed me in the right direction.
i should probably mention that input will actually be garbage data, not 0.
Thank you @Tau, you are right. I have updated my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.