[英]Function pointer not returning a value
We just learnt in school about function pointers in C and i wanted to try them out in a test program. 我们刚刚在学校里学习了C语言中的函数指针,我想在测试程序中尝试一下。 The idea is obviously pretty simple. 这个想法显然很简单。 However, when i try to use result = (*funcPtr)();
但是,当我尝试使用result = (*funcPtr)();
i get an STATUS_ACCESS_VIOLATION
exception but i can't tell what i did wrong. 我收到STATUS_ACCESS_VIOLATION
异常,但我不知道自己做错了什么。 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);
}
You forgot a &
before input in the scanf
. 您在scanf
输入之前忘记了&
。 Therefore scanf
writes not to the address of the input
variable, but to its value (and the variable is uninitialized a this point). 因此, scanf
不会写入input
变量的地址,而是写入其值(此时,变量未初始化)。
Change that line to: 将该行更改为:
scanf("%d", &input);
to pass a pointer to input
to scanf
and not the value of input
. 到一个指针传递给input
到scanf
和不是值input
。
And as already pointed out by other users, do not forget to handle inputs other than 1
and 2
. 并且正如其他用户已经指出的那样,不要忘记处理1
和2
以外的其他输入。 Otherwise you will call your uninitialized funcPtr
variable, which most likly results in a Segmentation fault. 否则,您将调用未初始化的funcPtr
变量,这很可能导致分段错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.