magicianz Registered User
#1

I'm currently doing a project that takes an input from the serial monitor in the processing compiler, converts it into a pulse sequence and transmits that to a distant receiver. It's quite easy to accomplish it with just a great dear of repetitive code but I hate doing that. The problem I'm currently having is that I want to make an array which contains numerous methods, but I cannot figure out how to do it!

E.g. Float array[] = { method1(), method2(), ....... } ;

I am constantly getting error messages with identifier I try. Im looking to find this out as it cuts out about 70 - 80 lines of repetitive stuff.

For anyone who doesn't know what processing is, it's a C based language used to programme the arduino micro-controllers.

Thanks!

Tillotson Registered User
#2

If the language is close to C, then your type signatures are probably wrong.


float sum(float a, float b)
{
        return a + b;
}

/* fpa is an array of pointers to (float, float) functions which return float */
float (*fpa[])(float, float) = { sum, sum };

Groinshot Registered User
#3

I have experience with C, and Arduino, but am more than prepared to be pulled up on this..
Can't just create an array of functions, it doesn't work. What you need to do is create an array of pointers, one pointer to each function, and store each pointer as a slot in the array. You can then call each function by dereferencing the pointer.....
See SO if that doesn't make any sense.....
However, I've never tried it on an arduino, so don't know if it will work or not.

1 person has thanked this post
Tillotson Registered User
#4

Groinshot said:

What you need to do is create an array of pointers, one pointer to each function, and store each pointer as a slot in the array. You can then call each function by dereferencing the pointer.


Exactly, the above code could be written:

float (*fpa[])(float, float) = { &sum, &sum };

To invoke these functions:

printf("%f\n", fpa[0](1.0, 2.0));
or

printf("%f\n", (*fpa[0])(1.0, 2.0));
I prefer the shorter syntax but the other might be clearer. It's interchangeable either way.

2 people have thanked this post
magicianz Registered User
#5

Thanks a lot to both of ye. Only really got to look at it properly today and, for the moment, its working perfectly!

 float (*arrayName[]) (float,float) = { func1, func2, func3,.....};
That works perfectly for me, just took a while to properly understand what you were saying. Thanks again! Saved me a lot of stress, none of the examples i've seen online are as clear

Want to share your thoughts?

Login here to discuss!