Lesmian
21
Q:

function pointer c

#include <stdio.h> 
// A normal function with an int parameter 
// and void return type 
void foo(int a) { 
    printf("foo: Value of a is %d\n", a); 
}

int add(int a, int b) {
	return a+b;
}

// Take function as argument
void baz(void (*fun)(int), int arg) {
	// call fun
  printf("baz: Calling func pointer with arg %d\n", arg);
  fun(arg);
}

int main() {
  	// Create pointers
  	void (*fun_a)(int) = &foo;
    void (*fun_b)(int) = foo;  // & removed 
  	int (*fun_c)(int, int) = add;
  
    (*fun_a)(10); // If you have the address, use *
  	fun_b(10);    // * removed
  	printf("fun_c(10, 20) = %d\n", fun_c(10,20));
    baz(foo, 10);
  
    // output:
    // foo: Value of a is 10
    // foo: Value of a is 10
    // fun_c(10, 20) = 30
    // baz: Calling func pointer with arg 10
    // foo: Value of a is 10
    return 0; 
}
4
myvar = 25;
foo = &myvar;
bar = myvar;
2
//Declaration of a pointer to a function that acccepts an integer 
//and also returns an integer.
int (*f_ptr)(int);

//Assignment of a function foo to the function pointer f_ptr declared above.
f_ptr = foo;

//Calling foo indirectly via f_ptr, passing the return value of foo to r.
int r = f_ptr(v);

//Assigning an address of a function to the function pointer f_ptr,
//then calling foo by dereferencing the function pointer.  
f_ptr = &foo;
int r = (*f_ptr)(v);
0

New to Communities?

Join the community