如何检索特定变量的地址?

How to retrieve the addresses of particular variables?

我有一些代码 - 我想看看特定变量是如何放入堆栈的。

#include <iostream>
using namespace std;

int fun(char b, long c, char d){
short p,q,r;
int y;
/***return &b,&c,&d,&p,&q,&r,&y;***/ - this one was for purpose of what should be returned, it is not valid code}

int main(){
fun('a',123,'b');
return 0;
}

预期结果将是特定变量的地址,这就是我使用操作数 & 的原因。 但是,我仍然不知道将它正确地放置在我的代码中的什么位置,即 MAIN 函数。

备注:函数实际上什么都不做,它只是计算机体系结构课程目的的练习。

#include <iostream>
using namespace std;

int fun(char b, long c, char d){
short p,q,r;
int y;
cout<<(void*)&b<<endl<<&c<<endl<<(void*)&d<<endl;
cout<<&p<<endl<<&q<<endl<<&r<<endl<<&y<<endl;}


int main()
{
fun('a',123,'b');
return 0;}

好的,我明白了。这就是解决方案。

如果您想捕获 fun 中的地址以查看它们在堆栈中的位置(或它们在内存中的任何位置),并且您想要 return 所有这些地址到 main,你可以使用这个:

#include <iostream>
#include <map>
using namespace std;

map<const char*, void*> fun(char b, long c, char d) {
  short p, q, r;
  int y;
  return {
    { "b", &b },
    { "c", &c },
    { "d", &d },
    { "p", &p },
    { "q", &q },
    { "r", &r },
    { "y", &y },
    { "b", &b }
  };
}

int main() {
  auto results = fun ('a', 123, 'b');
  for (auto p: results) {
    printf("%s is at %p\n", p.first, p.second);
  }
}

对我来说显示

b is at 0x7ffdec704a24
c is at 0x7ffdec704a18
d is at 0x7ffdec704a20
p is at 0x7ffdec704a36
q is at 0x7ffdec704a38
r is at 0x7ffdec704a3a
y is at 0x7ffdec704a3c

请记住,正如其他人指出的那样,您不能在 main 中使用这些地址!恕我直言,在 fun 本身内执行 printf 调用会好得多。但不用担心!希望这对您有所帮助。