那会错吗?如果是这样,为什么呢?输出是2500

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)

hac*_*cks 8

您获得奇怪输出的原因是未定义的行为.您将返回自动局部变量的地址,该函数在函数到达时将不再存在.

虽然,可以根据函数调用的堆栈帧给出输出的解释.由于最后一次调用是for function g并且传递给它2500的参数是,x函数的参数g在堆栈上分配并2500被推送到堆栈.当这个函数返回时,这个值从堆栈中弹出(虽然堆栈帧g在返回调用者后是无效的)并且它可以2500从它的堆栈帧返回它.


Sou*_*osh 5

在这两个函数中,您尝试返回函数中局部变量的地址.一旦函数完成执行并且控件返回到调用者,返回的地址就变为无效(即,变量超出范围),并且任何使用返回值的尝试都会调用未定义的行为.

如果你必须从一个函数返回一个地址并在调用者中使用它,你将需要一个通过动态内存分配器函数(例如malloc()和family)分配内存的指针.