0

I am learning the concepts of function pointers in C and was wondering how to use in structures.

Say for example I have:

struct math{ int a; int b; int (*ADD)(int, int); int (*subtract)(int, int); }; int add(int a ,int b) { return (a+b); } int main() { math M1; M1.a = 1; M2.b = 2; M2.ADD = add; } 

In this the function pointer ADD is pointing to function add. Is there a way to write a function similar to a constructor that will automatically point ADD to add ?

so that if write M1.construct()

it should do inside that

void construct() { ADD = add; } 

I dont want to keep writing for each objects the same lines. Is there a way for this ?

2
  • There is no way to add C++-style member functions to struct types in C. Commented Aug 31, 2014 at 2:17
  • 1
    In answer to your question about automatically pointing ADD to add, the answer is yes. Although, you may want to save it until you are quite comfortable with pointers, memory allocation, etc. The details can be found in Object oriented programming with ANSI-C. The class type construct from structures makes a quite interesting read. Commented Aug 31, 2014 at 2:48

1 Answer 1

2

The best you can do is to provide a function like this:

void math_construct(struct math *m, int a, int b) { m->a = a; m->b = b; m->ADD = add; } int main() { struct math m1; math_construct(&m1, 44, 55); } 

Or, alternatively, you can provide a function to allocate the memory for a struct math as well, but this will require you to use free() when you no longer need it:

struct math *math_new(int a, int b) { struct math *result = malloc(sizeof *result); // check whether result is NULL before continuing result->a = a; result->b = b; result->ADD = add; return result; } int main() { struct math *m1 = math_new(44, 55); // do something with m1 free(m1); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! That would do for me :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.