0

i am confused! are all of the following printf's the correct way to print the addresses of functions? Let me tell you my confusion as well. Everytime i run all of these printf's (that is, 1st printf, 2nd printf and 3rd printf), in output i get 02D4 02D4 02D4 but if i remove or comment of 1st and 2nd printf, i get folowing as output 02BA when i remove third printf statement, i am getting following output 02D0 Again when i uncomment all of these three, i get: 02D4 02D4 02D4 Why is one statement affecting the output of other printf line? Is this not really the address of function? I have heard that s and &s give the same value that is address (just like arrays). but here i am confused why s and &s are affected when i try to print b also, where b=s or &s.

#include<stdio.h>
#include<conio.h>
int s(int);
void main()
{
int a=10,*b;
clrscr();
b=s(a++);
b=&s;
printf("%p\n",s);       // 1st printf
printf("%p\n",&s);      //2nd printf
printf("%p\n",b);       //3rd printf
getch();
}
int s(int x)
{
return x;
}
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
gj1103
  • 127
  • 2
  • 10
  • 2
    You should not put a function pointer into a variable pointer (they're not guaranteed to be the same size), but other than that it seems OK. A special case of the C language is that a function name without a `&` gains one implicitly (personally I prefer to always make it explicit though) – Dave Jun 15 '14 at 13:43
  • 2
    (though, in the same way that you shouldn't cast a function pointer to a variable pointer, you shouldn't use one with the `%p` format. See this answer for a safe way to print a function pointer: http://stackoverflow.com/a/2741896/1180785) – Dave Jun 15 '14 at 13:45
  • 1
    As for why your addresses change, it's because you're recompiling the script! They could very well be different between compilations even if you made no changes to the code at all. – Dave Jun 15 '14 at 13:47
  • thanks @Dave. I got your point. – gj1103 Jun 15 '14 at 15:21

1 Answers1

2

The address of a variable or a function is not something you can depend on, as both the compiler and the operating system can influence where it ends up.

But supposing that the operating system always loads your executable code at the same address, if you change the length of code in the main() function, that may very well influence the starting address of the s() function. Consequently, you get a different result.

DrWatson
  • 418
  • 3
  • 9