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

How to retrieve the addresses of particular variables?

本文关键字:变量 地址 何检索 检索      更新时间:2023-10-16

我得到了一些代码 - 我想看看特定变量是如何放置在堆栈上的。

#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;
}

预期结果将是特定变量的地址,这就是我使用操作数 &. 但是,我仍然不知道将其正确放置在代码中的哪个位置,即主函数。

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

如果您想捕获fun中的地址以查看它们在堆栈中的位置(或它们在内存中的位置),并且您想将所有这些地址返回给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 %pn", 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调用会好得多。但不用担心!希望这有所帮助。

#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;}

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