简体   繁体   English

结构中的功能指针

[英]Function Pointer in Struct

How do you use Function Pointer in Struct? 如何在Struct中使用功能指针? Specifically, given the following example, the program compiles but crash on run-time: 具体来说,给出以下示例,该程序可以编译但在运行时崩溃:

In a header file 在头文件中

 #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_ */

In the C file: 在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);

}

Please advise me. 请建议我。

You're almost there: 你快到了:

struct functionDaemon *ftnAgent;

double  sum;

// Use 'sin()' as the pointed-to function
ftnAgent->fp = sin;

Your ftnAgent is just a non-initialized pointer. 您的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);

Here is a working example: 这是一个工作示例:

#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;
}

Edit 编辑

As you have this: 有了这个:

extern struct functionDaemon *ftnAgent;

I assume ftnAgent is instantiated somewhere else. 我假设ftnAgent已在其他地方实例化。 In this case, you don't need struct functionDaemon *ftnAgent; 在这种情况下,您不需要struct functionDaemon *ftnAgent; inside do_compute_sum as it will hide the already declared ftnAgent struct, so you will access the wrong (uninitialized) variable. do_compute_sum内部,因为它将隐藏已经声明的ftnAgent结构,因此您将访问错误的(未初始化)变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM