2

How do you use Function Pointer in 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:

#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.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
Ursa Major
  • 851
  • 7
  • 25
  • 47
  • 1
    You're using a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Sep 06 '13 at 17:42
  • 1
    Where is compute_sum defined? Also you do not allocate any memory for `ftnAgent`. – Joe Sep 06 '13 at 17:43

1 Answers1

10

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.

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. In this case, you don't need struct functionDaemon *ftnAgent; inside do_compute_sum as it will hide the already declared ftnAgent struct, so you will access the wrong (uninitialized) variable.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
  • 1
    Based on `extern struct functionDaemon *ftnAgent;`, I'd assume the OP was trying to define this somewhere else, but then hiding it with the local variable. – Joshua Taylor Sep 06 '13 at 17:45