Accessing array of function pointers - c

Following is the array of function pointers
(int) (*a[5]) (int);
int f1(int){};
...
is the following way of definition correct?
a = f1;
a + 1 = f2;
a + 2 = f3;
...
how do we call these functions?
*a(1) // is this correct???
*(a+1) (2)

#include <stdio.h>
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
int (*a[5]) (int);
a[0] = f1;
a[1] = f2;
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
}

What you call "definition" is just assignment, and as you are doing it, it is wrong, since you can't assign to arrays in C. You can only assign to individual array elements, correct would be a[0] = f1 etc.
Often for arrays of function pointers there is no need to assign them dynamically at run time. Function pointers are compile time (or link time) constants anyhow.
/* in your .h file */
extern int (*const a[5]) (int);
/* in your .c file */
int (*const a[5]) (int) = { f1, f2, f3 };
To simplify using function pointers a bit, the identifier for a f1 is equivalent to a pointer to the function &f1 and using a function pointer with parenthesis as in a[0](5) is the same as dereferencing the pointer and calling the resulting function (*(a[0]))(5).

you can write:
a[0]=&f1;
and call it as below:
a[0](1);
note that there is no need to use a pointer while the function is getting called.
If you insist on using a pointer, then you can anyhow do the below:
(*a[0])(1);

It is always better to use typedefs, (and all your functions need to have a common interface anyway and also to initialise at declaration time, where possible function arrays should also be const as a safety measure so:
#include <stdio.h>
typedef int (*mytype)();
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
const mytype a[5] = {f1,f1,f2,f2,f1};
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
return 0;
}

#include<stdio.h>
int (*a[5]) (int);
int f1(int i){printf("%d\n",i); return 0;}
int f2(int i){printf("%d\n",i); return 0;}
int f3(int i){printf("%d\n",i); return 0;}
int main(void)
{
a[0] = f1; // Assign the address of function
a[1] = f2;
a[2] = f3;
(*a[0])(5); // Calling the function
(*a[1])(6);
(*a[2])(7);
getchar();
return 0;
}

Related

can we have a double function pointer in C?

I am wondering that unlike the double pointers (int**) , can we have double function pointer?
I mean the function pointer pointing to the address of the another function pointer ?
I want something like
int add(int A , int B){
return A+B;
}
int main(void){
int (*funcpointerToAdd)(int,int) = add; // single function pointer pointing to the function add
printf("%d \n",funcpointerToAdd(2,3));
int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;
printf("%d \n",doubleFuncPointerToAdd(2,3));
return 0;
}
but this gives me an error called object ‘doubleFuncPointerToAdd’ is not a function or function pointer
is this possible to do this thing anyway ?
You can use pointers to pointers to functions, but you have to deference them once first:
int add(int A , int B){
return A+B;
}
int main(void){
int (*funcpointerToAdd)(int,int) = &add;
//By the way, it is a POINTER to a function, so you need to add the ampersand
//to get its location in memory. In c++ it is implied for functions, but
//you should still use it.
printf("%d \n",funcpointerToAdd(2,3));
int (**doubleFuncPointerToAdd)(int,int) = &funcpointerToAdd;
printf("%d \n",(*doubleFuncPointerToAdd)(2,3));
//You need to dereference the double pointer,
//to turn it into a normal pointer, which you can then call
return 0;
}
This is also true for other types:
struct whatever {
int a;
};
int main() {
whatever s;
s.a = 15;
printf("%d\n",s.a);
whatever* p1 = &s;
printf("%d\n",p1->a); //OK
//x->y is just a shortcut for (*x).y
whatever** p2 = &p1;
printf("%d\n",p2->a); //ERROR, trying to get value (*p2).a,
//which is a double pointer, so it's equivalent to p1.a
printf("%d\n",(*p2)->a); //OK
}

Passing function to function C [duplicate]

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}

C program returning array [duplicate]

This question already has answers here:
Declaring a C function to return an array
(5 answers)
Closed 9 years ago.
I am working on a very basic program where I want to return an integer array of length 2 to my main block. I can't get it to work though, and I was told that I may need pointers to do this. How do pointers work, and how can I use this in my program?
Here is my current code:
int[] return2();
int main() {
int a[2];
a = request();
printf("%d%d\n", a[0], a[1]);
return(0);
}
int[] request ()
{
int a[2];
a[0] = -1;
a[1] = 8;
return a;
}
You can't declare a function returning an array.
ISO/IEC 9899:1999
§6.9.1 Function definitions
¶3 The return type of a function shall be void or an object type other than array type.
C2011 will say essentially the same thing.
You shouldn't ever return a pointer to a (non-static) local variable from a function as it is no longer in scope (and therefore invalid) as soon as the return completes.
You can return a pointer to the start of an array if the array is statically allocated, or if it is dynamically allocated via malloc() et al.
int *function1(void)
{
static int a[2] = { -1, +1 };
return a;
}
static int b[2] = { -1, +1 };
int *function2(void)
{
return b;
}
/* The caller must free the pointer returned by function3() */
int *function3(void)
{
int *c = malloc(2 * sizeof(*c));
c[0] = -1;
c[1] = +1;
return c;
}
Or, if you are feeling adventurous, you can return a pointer to an array:
/* The caller must free the pointer returned by function4() */
int (*function4(void))[2]
{
int (*d)[2] = malloc(sizeof(*d));
(*d)[0] = -1;
(*d)[1] = +1;
return d;
}
Be careful with that function declaration! It doesn't take much change to change its meaning entirely:
int (*function4(void))[2]; // Function returning pointer to array of two int
int (*function5[2])(void); // Array of two pointers to functions returning int
int (*function6(void)[2]); // Illegal: function returning array of two pointers to int
int *function7(void)[2]; // Illegal: function returning array of two pointers to int
You better to understand how does pointer work. Here is a (bad) solution:
#include <stdio.h>
int* request(){
int a[2];
a[0] = -1;
a[1] = 8;
return a;
}
int main() {
int* a;
a = request();
printf("%d%d\n", a[0], a[1]);
return 0;
}
but there is a problem. since int a[2]; in int* request() is a local variable, there is no guarantee that the value returned will not be overwritten.
Here is a better solution:
#include <stdio.h>
void request(int* a){
a[0] = -1;
a[1] = 8;
}
int main() {
int a[2];
request(a);
printf("%d %d\n", a[0], a[1]);
return 0;
}
You have to return pointer to array of 2 integers from function.
#include
int(* request()) [2]
{
static int a[2];
a[0] = -1;
a[1] = 8;
return &a;
}
int main() {
int (*a) [2];
a = request();
printf("%d%d\n", *(*a+0), *(*a+1));
return 0;
}
The array int a[2] that you declare in request is only valid during the scope of that function, so returning it like that doesn't work, since once main gets its hands on it the array is no longer valid.
If you don't understand pointers, you're going to kind of have to to really get what's going on, but here is some code that will do what you want:
int* request();
int main() {
int* a; // a is a pointer to an int
a = request();
printf("%d%d\n", a[0], a[1]);
// we have to tell the program that we're done with the array now
free(a);
return(0);
}
int* request ()
{
// allocate space for 2 ints -- this space will survive after the function returns
int* a = malloc(sizeof(int) * 2);/
a[0] = -1;
a[1] = 8;
return a;
}
You can do as others suggest and allocate memory via malloc to return a pointer. You should also consider something like the following:
struct values {
int val1;
int val2;
};
struct values request();
int main() {
struct values a;
a = request();
printf("%d%d\n", a.val1, a.val2);
return(0);
}
struct values request ()
{
struct values vals;
vals.val1 = -1;
vals.val2 = 8;
return vals;
}
Structures are passed and returned by value (meaning they are copied) and can sometimes be easier and safer depending on the type of data contained within the structures.
To return the array, you must dynamically allocate it.
Try this instead (Observe the changes) :
int* request();
int main() {
int *a;
a = (int *)request();
printf("%d %d\n", a[0], a[1]);
return(0);
}
int* request() {
int *a = malloc(sizeof(int) * 2);
a[0] = -1;
a[1] = 8;
return a;
}

c - initialize an array of pointers to functions

I want to initialize an array of size 5 pointers that holds pointers to functions that have no parameters and which returns an int (could be any function that facilitate these requirements).
This is what i tried thus far but i get a syntax error:
int (*func)() fparr[5] = int (*func)();
What is wrong with this syntax?
If the function you want to supply as the default contents of the array is called func, then
you better use a typedef,
you have to use an array initializer
Consider:
typedef int (*IntFunc)(void);
IntFunc fparr[5] = { func, func, func, func, func };
Or the less readable way, if you prefer to avoid typedef:
int (*fparr[5])(void) = { func, func, func, func, func };
Because you are not actually initialising an array of function pointers ... try:
int (*fparr[5])(void) = { func1, func2, func3, func4, func5 };
Step 1:
define the signature of the functions as a type FN:
typedef int (*FN)();
Step2:
define the 5 functions with the FN signature:
int f1(void) { ; }
int f2(void) { ; }
...
Step 3:
define and initialize an array of 5 functions of type FN:
FN fparr[5] = {f1,f2,f3,f4,f5}
otherwise:
If you do not want to define a separate signature, you can do it -- as said before -- so:
int ((*)fpar []) () = {f1,f2, ...}
If you know the number of functions from the array at the moment of declarations, you do not need to write 5, the compiler allocated this memory for you, if you initialize the array at the same line as the declaration.
Well, I'm late...
#include <stdio.h>
int fun0()
{
return 0;
}
int fun1()
{
return 1;
}
int fun2()
{
return 2;
}
int main(int argc, char* argv[])
{
int (*f[]) (void) = {fun0, fun1, fun2};
printf("%d\n", f[0]());
printf("%d\n", f[1]());
printf("%d\n", f[2]());
return 0;
}
An array of function pointers can be initialized in another way with a default value.
Example Code
#include <stdio.h>
void add(int index, int a, int b){
printf("%d. %d + %d = %d\n", index, a, b, a + b);
}
void sub(int index, int a, int b){
printf("%d. %d - %d = %d\n", index, a, b, a - b);
}
int main(){
void (*func[10])(int, int, int) = {[0 ... 9] = add};
func[4] = sub;
int i;
for(i = 0; i < 10; i++)func[i](i, i + 10, i + 2);
}
If you run the above program, you will have the below output. All elements are initialized with function add, but 4th element in array is assigned to function sub
Output
0. 10 + 2 = 12
1. 11 + 3 = 14
2. 12 + 4 = 16
3. 13 + 5 = 18
4. 14 - 6 = 8
5. 15 + 7 = 22
6. 16 + 8 = 24
7. 17 + 9 = 26
8. 18 + 10 = 28
9. 19 + 11 = 30
I just add a bit more to the above answers. Array of function pointers can be indexed by an enum variable, showing the type of operation for each index. Take a look at the following example. Here, we use tyepdef for function pointer operator. Then we create an array of this function pointer called act. Finally, we initialize the array to the increment and decrement functions. In this case, index 0 is referred to increment and index 1 is referred to decrement. Instead of using this raw indexing, we use enum which has INCR, and DECR, corresponding to index 0, 1.
#include<stdio.h>
#include<stdlib.h>
typedef void (*operate)(int *, int);
void increment(int *, int);
void decrement(int *, int);
enum {
INCR, DECR
};
int main(void){
int a = 5;
operate act[2] = {increment,decrement};
act[INCR](&a,1);
printf("%d\n",a);
act[DECR](&a,2);
printf("%d\n",a);
return 0;
}
void increment(int *a, int c){
*a += c;
}
void decrement(int *a, int c){
*a -= c;
}
Here is a working example showing the correct syntax:
#include <stdio.h>
int test1(void) {
printf("test1\n");
return 1;
}
int test2(void) {
printf("test2\n");
return 2;
}
int main(int argc, char **argv) {
int (*fparr[2])(void) = { test1, test2 };
fparr[0]();
fparr[1]();
return 0;
}
Example code:
static int foo(void) { return 42; }
int (*bar[5])(void) = { foo, foo, foo, foo, foo };
Note that the types int (*)() and int (*)(void) are distinct types - the former denotes a function with a fixed but unspecified number of arguments, whereas the latter denotes a function with no arguments.
Also note that the C declarator syntax follows the same rules as expressions (in particular operator precedence) and is thus read inside-out:
bar denotes and array (bar[5]) of pointers (*bar[5]) to functions (int (*bar[5])(void)). The parens (*bar[5]) are necessary because postfix function calls bind more tightly than prefix pointer indirection.

How do you pass a function as a parameter in C?

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}

Resources