answer action

Can’t find an answer?

Make use of a qualified tutor to get the answer

Tom
6
Q:

C : c function pointer

Features

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
Your Answer

Tags

New to Communities?

Join the community