C语言中的typedef函数指针
我只是在试验函数的C语言中的typedef函数指针,c,function,pointers,function-pointers,typedef,C,Function,Pointers,Function Pointers,Typedef,我只是在试验函数的typedef。我不清楚为什么在我的main()函数中删除DISPLAY周围的括号会导致此代码崩溃: #include <stdio.h> #include <stdlib.h> typedef void (*DISPLAY) (int*); void display(int* data) { printf("%d\n", *data); } void displayThis(int *val, DISPLAY func_displ
typedef
。我不清楚为什么在我的main()
函数中删除DISPLAY
周围的括号会导致此代码崩溃:
#include <stdio.h>
#include <stdlib.h>
typedef void (*DISPLAY) (int*);
void display(int* data) {
printf("%d\n", *data);
}
void displayThis(int *val, DISPLAY func_display) {
func_display (val);
}
int main() {
int x = 3;
/*DISPLAY disp = &display;
disp(&x);*/
displayThis(&x, DISPLAY display);
return 0;
}
以下是在DISPLAY
周围加括号的版本,其工作原理与预期一致:
#include <stdio.h>
#include <stdlib.h>
typedef void (*DISPLAY) (int*);
void display(int* data) {
printf("%d\n", *data);
}
void displayThis(int *val, DISPLAY func_display) {
func_display (val);
}
int main() {
int x = 3;
/*DISPLAY disp = &display;
disp(&x);*/
displayThis(&x, (DISPLAY) display);
return 0;
}
bash-3.2$ gcc -g display.c
bash-3.2$ ./a.out
3
为什么周围的括号显示
很重要?有人能帮我更好地了解发生了什么吗
谢谢。
Andy带括号的是类型转换,这是一种表达式类型。没有它们,它在语法上是一个声明,不能出现在函数调用的参数列表中。更简单的方法是删除显示:
displayThis(&x,DISPLAY)代码>,因为函数类型匹配,所以不需要强制转换。在我看来,最好不要强制转换,因为如果函数类型不匹配,您将在运行时得到编译错误,而不是未定义的行为。@Tomkarze请将您的注释作为答案,以便用户3512999可以标记它。克里斯的笔记也应该考虑。
bash-3.2$ gcc -g display.c
bash-3.2$ ./a.out
3