如何检索特定变量的地址?
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;
}
预期结果将是特定变量的地址,这就是我使用操作数 &. 但是,我仍然不知道将其正确放置在代码中的哪个位置,即主函数。
备注:函数实际上什么都不做,它只是计算机体系结构课程目的的练习。
如果您想捕获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;}
好的,我现在明白了。这就是解决方案。
相关文章:
- 附加调试器并以编程方式获取变量地址 Visual Studio
- 变量地址的运算符[]是如何工作的
- C 给出了一个字符串列表,如何从类中获取各个变量地址
- 从函数返回变量地址时如何修复"与局部变量关联的堆栈内存地址"?
- 获取封装在命名空间中的静态变量地址
- 为什么分配的变量地址之间相差 16 个字节?
- 为什么在循环中定义的变量地址在每次迭代中都保持不变
- 是否可以使用指向语句中声明的变量地址的指针"if"
- 字符串从变量(&变量)地址的长度 - 嵌入式C
- 汇编:C++堆栈变量地址不同/错误?
- x 在变量地址中的意义是什么?
- 在哪里放置 HW BP 以捕获全局变量地址损坏
- C++变量地址不匹配
- 重载 std::ostream 运算符<<未调用,stream 获取变量地址而不是对象
- std矢量包含指针和变量地址.清理
- 注册变量地址
- 使用内联程序集获取变量地址
- 如果用调试信息编译,则通过其名称获取全局变量地址
- 如何在Visual Studio中复制变量地址
- 当堆栈内存中的变量地址分配给数据段或堆内存中的指针时,是否有任何错误?