문제

I am trying to do something like

#include <iostream>

using namespace std;

void foo () {
  void (*fooptr) (void) = foo;
  cout << fooptr << endl;
}

int main () {
  void (*fooptr) (void) = foo;
  foo ();
  return 0;
}

My intent is to see the value of function pointers. If I look up for the address of any function in the main () function it makes sense that the function isn't called, It might have not been allocated the memory in the function call stack. But when I call the function and try to see the value of pointer. It still shows the same result 1. Any explanation? I might not be printing the address of the called function itself. Is there any pointer like this like we have in classes. So that we can see the address of itself?

도움이 되었습니까?

해결책

The standard stream types don't overload << for function pointers, only for regular pointers. You see the value 1 because a function pointer is implicitly convertible to bool, and there is an overload for bool, so that is chosen.

To print the address, you could convert it to a regular (object) pointer:

cout << reinterpret_cast<void*>(fooptr) << std::endl;

Note that this isn't completely portable: according to the standard, it's conditionally-supported, with an implementation-defined meaning. But it should give the expected address on any sensible implementation on mainstream platforms that store functions in regular memory. For more portability, you might convert to intptr_t or uintptr_t; but you'd need a bit of extra work if you want it to be formatted like a pointer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top