简体   繁体   English

想了解函数变量如何存储在堆栈中

[英]Want to understand how function variables are stored in stack

I am trying to understand how variables are stored in the memory stack and what the printf statements are printing. 我试图了解如何将变量存储在内存堆栈中以及printf语句正在打印什么。 Your insight in this will be highly appreciated. 您对此的见识将受到高度赞赏。 Thank you. 谢谢。

Ideone link http://ideone.com/uWvPpX Ideone链接http://ideone.com/uWvPpX

#include <stdio.h>

int main(void) {

    foo("%x");
    return 0;
}

void foo(char *str)
{

    char c='c';
    printf(str);

    printf("\n%x",&c);
}

%x is a format specifier indicates you want to print in lower-case hexadecimal. %x是一种格式说明符,指示您要以小写十六进制格式打印。 So when you don't specify data in the first printf the result is undefined. 因此,当您在第一个printf未指定数据时,结果是不确定的。 Even though the code compiles - it is incomplete! 即使代码可以编译-它也不完整!

So let us fix the code first- here is the revised code 因此,让我们先修复代码-这是修改后的代码

#include <stdio.h>

void foo(char *str);

int main(int argc, char* argv[])
{

    foo("%x");
    return 0;
}

void foo(char *str)
{

    char c='c';
    printf(str,c);

    printf("\n%x",&c);
}

Now to answer your questions "how variables are stored in the memory stack" The stack pointer registers the top of the stack,every time a value is pushed on to or popped out of the stack - the stack pointer is adjusted to point to the free memory. 现在回答您的问题“如何将变量存储在内存堆栈中”每次将值压入或弹出堆栈时,堆栈指针都会注册堆栈的顶部-调整堆栈指针使其指向空闲状态记忆。 And then there is the stack frame, it corresponds to a call to the function which has not yet terminated with a return. 然后是堆栈帧,它对应于尚未以返回终止的函数调用。 在此处输入图片说明

the other part was "what the printf statements are printing." 另一部分是“ printf语句正在打印什么”。 The first parameter in the printf is a format specifier, the second parameter onwards are the data that are to be used for those format specifier(s). printf中的第一个参数是格式说明符,第二个参数开始是要用于那些格式说明符的数据。 When you did not have the c in your first original printf - it just picked up the adjacent int and printed that for %x that was specified. 当您的第一个原始printf中没有c时-它只是拿起相邻的int并将其打印为指定的%x。 In the revised first printf I made it print he cvalue of c in hexadecimal. 在修订的第一份printf中,我以十六进制打印出c的c值。 In your second printf you make it print the address of C variable that is in the stack. 在第二个printf中,使它打印堆栈中C变量的地址。

Check these links for further details - https://en.wikipedia.org/wiki/Call_stack#Structure Also other Stackoverflow Q&As that show up on the right pane. 检查这些链接了解更多详情- https://en.wikipedia.org/wiki/Call_stack#Structure另外其他#1 Q&至于在右侧窗格中显示出来。

TO 8086 platforms: As you can read here , stack is the runtime/call stack, each function local vars are stored in the current procedure stack frame. TO 8086平台:如您在这里所读,stack是运行时/调用栈,每个函数的本地var存储在当前过程栈框架中。 read more about runtime/call stack here 在此处阅读有关运行时/调用堆栈的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM