Urs*_*jor 1 c c++ struct pointers
如何在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_ */
Run Code Online (Sandbox Code Playgroud)
在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);
}
Run Code Online (Sandbox Code Playgroud)
请建议我.
Nem*_*ric 10
你快到了:
struct functionDaemon *ftnAgent;
double sum;
// Use 'sin()' as the pointed-to function
ftnAgent->fp = sin;
Run Code Online (Sandbox Code Playgroud)
你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);
Run Code Online (Sandbox Code Playgroud)
这是一个工作示例:
#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;
}
Run Code Online (Sandbox Code Playgroud)
编辑
你有这个:
extern struct functionDaemon *ftnAgent;
Run Code Online (Sandbox Code Playgroud)
我假设ftnAgent在其他地方实例化.在这种情况下,您不需要struct functionDaemon *ftnAgent;在内部do_compute_sum,因为它将隐藏已经声明的ftnAgent结构,因此您将访问错误的(未初始化的)变量.
| 归档时间: |
|
| 查看次数: |
9068 次 |
| 最近记录: |