这是我老师的代码:

#include <stdio.h>
void foo1(int xval){
    int x;
    x = xval;
    printf("Address of x: %p\nValue of x: %d\n", &x, x);
}
void foo2(int dummy){
    int y;
    printf("Address of y: %p\nValue of y: %d\n", &y, y);
}
int main(void){
    foo1(7);
    foo2(11);
    return 0;
}


这是生成的输出:



谁能解释我为什么?

最佳答案

stack after call                     stack after call
to foo1()                            to foo2()
+----------------+                   +----------------+    |
| stack frame of |                   | stack frame of |    |
| main()         |                   | main()         |    v
++++++++++++++++++ <-- same addr --> ++++++++++++++++++   stack
| stack frame of |                   | stack frame of |   growth
| foo1()         |                   | foo2()         |
+----------------+                   +----------------+


现在,foo1()堆栈框架中x的地址与foo2()堆栈框架中y的地址相同。

这是因为两个函数具有相同数量和类型的参数和局部变量(它们被压入堆栈)。在调用foo1()时,将x地址(在您的情况下为0x7fff63387a84)中的值设置为7。该值将持续存在,因为在foo1()和foo2()之间没有其他函数调用。

注意此答案仅供您理解。您不应依赖y的值,因为y的值尚未初始化(如前面的注释中所指出)。这仅仅是偶然现象。我建议您仔细研究一下堆栈框架的形成方式。

关于c - 在C中使用指针进行练习会产生含糊的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50841792/

10-12 20:47