0

I tried this code

  1 #include <stdio.h>
  2
  3 int  sum(int a,int b)
  4 {
  5  printf ("\nFun sum called");
  6  return a+b;
  7 }
  8
  9 int main()
 10 {
 11  int a=5;
 12  int b=6;
 13  printf("\n 1. %d",sum(a,b));
 14  printf("\nAddress of sum : %p",&sum);
 15  int (*fptr)(int,int) = NULL;
 16  fptr = &sum;
 17  printf("\n 2. %d",fptr(a,b));
 18  printf("\nAddress of fptr is %p and fptr is %p",fptr,*fptr);
 19  return 1;
 20 }

and my output was

 Fun sum called
 1. 11
 Address of sum : ***0x400498***
 Fun sum called
  2. 11
 ***Address of fptr is 0x400498 and fptr is 0x400498***

Why is it that the address of function pointer and content held by the address inside function pointer appear to be the same?

They should be different! Am I missing something?

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
0aslam0
  • 1,797
  • 5
  • 25
  • 42

2 Answers2

1

No, they shouldn't be different, because you wrote:

fptr = &sum;

So the fptr points to the address of sum function. I think you want to get the address of function pointer, not the address of what function pointer points to, so you need to print: &fptr. This will be different.

TL;DR version: fptr, *fptr, &fptr - you need to know the difference between this.

python
  • 198
  • 1
  • 5
  • 13
1

fptr is not the address of this variable, it is the value of this variable.

Since you set fptr = &sum, you are essentially executing:

printf("\nAddress of sum is %p and sum is %p",&sum,sum);

And indeed, the address and the value of a symbol that represents a function are identical.


It's worth noting that the same behavior applies for a symbol that represents an array.

The common thing about those symbols (functions and arrays) is that they are constant.

In other words, once you've declared such symbol, you cannot set it to a different value.


If you want to compare the address and the value of fptr, then you should execute:

printf("\nAddress of fptr is %p and fptr is %p",&fptr,fptr);

Unless you set fptr = &fptr, this will surely print two different values.

barak manos
  • 29,648
  • 10
  • 62
  • 114