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.

2
  • 1
    You're using a reserved identifier. Commented Sep 6, 2013 at 17:42
  • 1
    Where is compute_sum defined? Also you do not allocate any memory for ftnAgent. Commented Sep 6, 2013 at 17:43

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.