Thi*_*raj 5 c pointers return-value
以下代码的输出是2500.它包含指针.有人可以给出正确的解释吗?为什么打印为2500?它是通过指针声明还是有另一个原因?
#include <stdio.h>
/* Two functions include and they are operated by main function */
int *f(int x) {
/* Creates an variable */
int p;
p = x;
return &p;
}
/* Here the initialization of the function g */
int *g(int x) {
/* Creates an variable */
int y;
y = x;
return &y;
}
/* This creates two pointers called x and y */
int main() {
int *x, *y;
/* Here call the functions f and g */
x = f(100);
/* Here call the function g */
y = g(2500);
/* How does it print 2500? */
/* print the value of x */
printf("%d \n", *x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您获得奇怪输出的原因是未定义的行为.您将返回自动局部变量的地址,该函数在函数到达时将不再存在.
虽然,可以根据函数调用的堆栈帧给出输出的解释.由于最后一次调用是for function g并且传递给它2500的参数是,x函数的参数g在堆栈上分配并2500被推送到堆栈.当这个函数返回时,这个值从堆栈中弹出(虽然堆栈帧g在返回调用者后是无效的)并且它可以2500从它的堆栈帧返回它.