会是这样错了吗?如果是的话,为什么呢?输出为2500 [英] would that be wrong? And if so why is it? The output is 2500

查看:88
本文介绍了会是这样错了吗?如果是的话,为什么呢?输出为2500的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code的产量是2500它包含指针。有人可以给这一个适当的解释吗?为什么它打印为2500?它来通过指针声明或有另一种原因是什么?

的#include<&stdio.h中GT;/ *两个功能包括它们由主要功能操作* /为int * F(INT X){
    / *创建一个变量* /
    INT磷;
    P = X;
    返回&安培; P;
}/ *这里,函数g *的初始化/
为int *克(INT X){
    / *创建一个变量* /
    诠释Ÿ;
    Y = X;
    返回&安培; Y;
}/ *这将创建两个指针名为x和y * /
诠释主(){
    INT * X,* Y;
    / *这里调用函数f和g * /
    X = F(100);
    / *这里调用函数g * /
    Y =克(2500);
    / *它是如何打印2500? * /
    / *打印X *值/
    的printf(%d个\\ N,* X);
    返回0;
}


解决方案

原因你越来越怪异输出为未定义的行为。您正在返回自动局部变量将不复存在一次函数达到其最终的地址。

虽然,对输出的解释可在函数调用的堆栈帧的形式给出。由于最后一次通话是功能先按g ,并传递给它的参数是 2500 ,参数 X 先按g 被分配在堆栈和 2500 被压入堆栈。当这个函数返回时,这个值从栈中弹出(尽管堆栈帧先按g 是返回给调用者无效后),它可能会返回此 2500 从它的堆栈帧。

The output of the below code is 2500. It contains pointers. Can someone give a proper explanation of this? Why does it print as 2500? Does it come through the pointer declaration or is there another reason?

#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;
}

解决方案

The reason you are getting weird output is undefined behavior. You are returning the address of automatic local variable which will no longer exist once function reach its end.

Although, the explanation for the output can be given in terms of stack frame of function call. Since the last call is for function g and the argument passed to it is 2500, the parameter x of function g is allocated on stack and 2500 is pushed to the stack. When this function return, this value popped from the stack (though the stack frame for g is invalid after return to the caller) and it may return this 2500 from its stack frame.

这篇关于会是这样错了吗?如果是的话,为什么呢?输出为2500的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆