无法理解让我们C静态存储类示例 [英] Not able to understand Let us C static storage class example

查看:105
本文介绍了无法理解让我们C静态存储类示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能够通过亚什万特Kanetkar了解咱们的例子我们C。这里是code片断:

I am not able to understand an example in Let us C by Yashwant Kanetkar. Here is the code snippet:

main()
{
    int *j;
    int *fun();
    j = fun();
    // If we add a function call here, the print statement prints a garbage value.
    printf("\n%d",*j);
}

int *fun()
{
    int k = 35;
    return (&k);
}

现在在上面code,我无法理解其在打印垃圾值printf语句结果前,函数调用原因。我有作为返回值指向堆栈中的存储位置,不顺心的事时,另一个功能是打印该值之前调用一个模糊的概念。但我不能够清楚地想象这里会发生什么。请帮助。

Now in the above code, I am not able to understand why having a function call before the printf statement results in printing a garbage value. I have a vague idea that as the returned value points to a memory location in the stack, something goes wrong when another function is called before printing this value. But I am not able to clearly visualize what happens here. Please help.

推荐答案

在您的code

int *fun()
{
    int k = 35;
    return (&k);
}

您从乐趣返回局部变量的地址()。返回值的任何使用导致未定义行为

you're returning the address of a local variable from fun(). Any usage of the return value leads to undefined behaviour.

要解释,一旦功能乐趣()执行完毕,不存在 K 的存在。因此,试图用类似&放大器;说明k 无效

To explain, once the function fun() finishes execution, there is no existence of k. So , trying to use something like &k is invalid.

注:无论是在那个特定的书提供的解释[相关堆放冲洗左右],是不是在C标准

这篇关于无法理解让我们C静态存储类示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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