Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use address of function in function pointer? [duplicate]

Tags:

c

pointers

My following code is working fine. But I have little doubt, please see //Comment1 and //Comment2

#include<stdio.h>
#include<string.h>

struct PTR
{
    int (*funptr)(int);
};

int fun1(int)
{
    printf("Fun1\n");
    return 0;
}

int fun2(int)
{
    printf("Fun2\n");
    return 0;
}

int main()
{
    PTR p;
    p.funptr = &fun1; //Comment1
    p.funptr(5);

    printf("\n");

    p.funptr = fun2; //Comment2
    p.funptr(5);


  return 0;

}

Output : Fun1 Fun2

There is no problem in output.

At comment1 '&' opertor is used, so we are expllicing telling to get address, in comment2, we are not using '&', so which one is correct way?

like image 797
Pranit Kothari Avatar asked Nov 02 '22 07:11

Pranit Kothari


1 Answers

'&' is optional when taking the address of function。

like image 138
SpadeAce Avatar answered Nov 15 '22 05:11

SpadeAce