It would be nice if, instead of just making unhelpful, and often insulting, comments, you actually helped people. Is it not obvious this was a simple typo?
I don't understand how that can work. Don't you need
foo(12);
(*funcptr)(12);
to demonstrate your method ?
No. funcptr is a pointer to a function which takes a single int argument, and returns nothing. In setup, funcptr is initialized to point to the function foo(). The two lines in loop() show two different, but exactly equivalent, ways of "de-referencing" funcptr to call foo(), passing 12 as the argument.
Function pointers is pretty advanced c, really not for beginners, but the question was asked....
It would be nice if, instead of just making unhelpful, and often insulting, comments, you actually helped people. Is it not obvious this was a simple typo?
Well, yes, it was obvious that there was some typo made. As to what you intended, no, I'm not a mind reader, so I can't guess what you intended.
So I tried to modify Ray’s code in order to be able to iterate over an array of functions.
Yet, somewhere is an error, probably in one of the commented lines. What needs to be corrected?
When you get a compile error, scroll the error window up to the FIRST error. It tells you exactly where the error is. In this case:
sketch_jan13a.ino: In function 'void setup()':
sketch_jan13a.ino:12:34: error: expected primary-expression before ']' token
The 12:34 means line 12, character 34 in the source code. It found a ']' where it was not legal to have one, which is a strong clue that your initialization was not valid.
The function pointer syntax can get kinda ugly. It cleans up a lot if you use typedef to define a new type for the function pointer:
typedef void (*foo_ptr_t)( int );
This declares a new variable, foo_ptr_t, of type "pointer to function which takes a single int arguement, and returns nothing". You can now use this new type just as you do all built-in types.
The arrany of function pointers becomes:
foo_ptr array_with_pointer_to_function[];
And you can initialize and call one of the functions like this:
The order of clauses in that for statement is wrong. Even if it were correct, the loop would iterate 3 times, executing the three functions in the array. Of course, there AREN’T three functions, so who knows what the hell would happen when the third call was made.
@PaulS
Just a minor glitch.
Initially I had written the sketch and tested it with three functions, an array of three and of course the loop you mention with “…i<3”.
For clarity / not blowing up space for the post here I then removed the last function and shortened the array - but forgot to shorten the for loop.
@Kevin77: The Right-Left Rule can be found in my C Programming Guide book, but that's from the 1980's. It's used to parse complex data definitions. You can find a summary at: