C++ 指向函数的指针怎么能指向不';还不存在于记忆中吗?为什么原型有不同的地址?

C++ 指向函数的指针怎么能指向不';还不存在于记忆中吗?为什么原型有不同的地址?,c++,memory,memory-management,function-pointers,function-prototypes,C++,Memory,Memory Management,Function Pointers,Function Prototypes,据我所知,函数只有在主函数中调用后的运行时才会添加到堆栈中 那么,如果一个函数的指针在内存中不存在,它怎么可能有一个函数的内存地址呢 例如: using namespace std; #include <iostream> void func() { } int main() { void (*ptr)() = func; cout << reinterpret_cast<void*>(ptr) << endl; //prints

据我所知,函数只有在主函数中调用后的运行时才会添加到堆栈中

那么,如果一个函数的指针在内存中不存在,它怎么可能有一个函数的内存地址呢

例如:

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
}
using namespace std;
#include <iostream>

void func();

int main() {
  void ( *ptr )() = func;
  cout << reinterpret_cast<void*>(ptr) << endl;
}

void func(){
}
使用名称空间std;
#包括
void func(){
}  
int main(){
无效(*ptr)(=func;
cout函数始终在内存中,但不在堆栈上。它们是与程序其余部分一起加载的代码的一部分,并被放入内存的一个特殊只读段中


调用函数时,堆栈上会保留局部变量(包括参数)的空间。

谢谢。这完全有道理。您所说的文本区域是内存部分的正式名称吗?@KacyRaye是的,它是“文本”段。非常感谢!我不知道文本区域实际上有内存地址。就像我从来没有想到的那样,因为大多数时候人们谈论堆或堆栈。这实际上也回答了我的第二个问题,因为实现的函数位于文本区域的不同部分。谢谢!