如何在Struct中使用函数指针? 具体来说,给出以下示例,程序编译但在运行时崩溃:
在头文件中
#ifndef __FUNCTION_IN_STRUCT_H_
#define __FUNCTION_IN_STRUCT_H_
struct functionDaemon {
int id;
//double (*funcp); // function pointer
double (*fp)(double); // Function pointer
};
// #define NULL 'V'
#endif /* _FUNCTION_IN_STRUCT_H_ */
在C档案中:
#include <math.h>
#include <stdio.h>
#include "function_in_struct.h"
extern struct functionDaemon *ftnAgent;
void do_compute_sum (void) {
void* agent;
// struct functionDaemon *ftnAgent = (struct functionDaemon *) agent;
struct functionDaemon *ftnAgent;
double sum;
// Use 'sin()' as the pointed-to function
ftnAgent->fp = sin;
sum = compute_sum(ftnAgent->fp, 0.0, 1.0);
printf("sum(sin): %f\n", sum);
}
请告诉我。
答案 0 :(得分:10)
你快到了:
struct functionDaemon *ftnAgent;
double sum;
// Use 'sin()' as the pointed-to function
ftnAgent->fp = sin;
您的ftnAgent
只是一个未初始化的指针。
struct functionDaemon ftnAgent;
double sum;
// Use 'sin()' as the pointed-to function
ftnAgent.fp = sin;
sum = compute_sum(ftnAgent.fp, 0.0, 1.0);
这是一个有效的例子:
#include <math.h>
#include <stdio.h>
struct functionDaemon {
int id;
//double (*funcp); // function pointer
double (*fp)(double); // Function pointer
};
int main()
{
struct functionDaemon f;
f.fp = sin;
printf("%f\n", (f.fp)(10));
return 0;
}
修改强>
你有这个:
extern struct functionDaemon *ftnAgent;
我认为ftnAgent
在其他地方被实例化。在这种情况下,struct functionDaemon *ftnAgent;
内部不需要do_compute_sum
,因为它会隐藏已经声明的ftnAgent
结构,因此您将访问错误的(未初始化的)变量。