I'm C Newbie. Please tell me how to use a function pointer

Asked 2 years ago, Updated 2 years ago, 108 views

Why is the pointer so hard? It's hard to use a normal pointer. A function pointer? How do I turn over the factor?

Please tell me how to use it, not too difficult ㅜ<

c function-pointer

2022-09-22 22:23

1 Answers

To write a function pointer, you must have a function, so let's create a function first. I simply took two integer factors and made a function that returns the sum of the two.

int addInt(int n, int m) {
    return n+m;
}

Then define the function pointer. addInt receives two factors, so this pointer also needs to receive two functions It must be int type since int is returned.

int (*functionPtr)(int,int);

Finally, point this pointer to addInt.

functionPtr = &addInt;

So let's use this function pointer. I got 5 back by adding 2 and 3.

int sum = (*functionPtr)(2, 3); // sum == 5

It's not much different when you pass the pointer to another function

int add2to3(int (*functionPtr)(int, int)) {
    return (*functionPtr)(2, 3);
}

You can also create a function that returns a function pointer

int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d\n", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}


int main(){
    int (*myfptr)(int,int) = functionFactory(6);
    printf("%d", (*myfptr)(2,3));
}

If the code looks dirty, you can use typedef to define the function pointer as a different name

typedef int (*myFuncDef)(int, int);

myFuncDef functionFactory(int n){
    printf("Got parameter %d\n", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}


int main(){
    myFuncDef myfptr = functionFactory(6);
    printf("%d", (*myfptr)(2,3));
}


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.