我有一些代码 - 我想看看特定变量是如何放置到堆栈中的。
#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 函数。
备注:函数实际上什么都不做,它只是计算机体系结构课程目的的练习。
如果您想捕获其中的地址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 %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
! 恕我直言,只在其printf
内部进行调用会好得多fun
。不过不用担心!希望这会有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句