【发布时间】:2013-06-30 04:17:17
【问题描述】:
据我所知,函数在主函数中调用后直到运行时才会被添加到堆栈中。
那么如果一个函数的指针在内存中不存在,它怎么能有函数的内存地址呢?
例如:
using namespace std;
#include <iostream>
void func() {
}
int main() {
void (*ptr)() = func;
cout << reinterpret_cast<void*>(ptr) << endl; //prints 0x8048644 even though func never gets added to the stack
}
另外,下一个问题对我来说不太重要,所以如果你只知道我第一个问题的答案,那很好。但是不管怎样,为什么我声明一个函数原型并在main之后实现函数时,指针的值(函数的内存地址)会不同呢?
在第一个示例中,无论我运行多少次,它都会打印出 0x8048644。 在下一个示例中,无论我运行多少次,它都会打印出 0x8048680。
例如:
using namespace std;
#include <iostream>
void func();
int main() {
void ( *ptr )() = func;
cout << reinterpret_cast<void*>(ptr) << endl;
}
void func(){
}
【问题讨论】:
标签: c++ memory memory-management function-pointers function-prototypes