【发布时间】:2013-09-06 17:40:41
【问题描述】:
如何在 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);
}
请给我建议。
【问题讨论】:
-
您使用的是reserved identifier。
-
compute_sum 在哪里定义?你也没有为
ftnAgent分配任何内存。