什么将是下面的C程序的输出? [英] What will be the output of following C program?

查看:119
本文介绍了什么将是下面的C程序的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的char *的getString()
{
    烧焦海峡[] =我会被印?
    返回海峡;
}
诠释的main()
{
    的printf(%S的getString());
    的getchar();
}

不应在输出中将我印? ?相反,输出出来是一些垃圾值。为什么会这样呢?


解决方案

 字符海峡[] =我会被印?

是一个局部声明。它被限制在功能的getString()。当你离开的功能,海峡[] 将被折叠。

所以你想它来打印数据。显然,你的垃圾价值!

要避免这一点 -

 的char *海峡=将我印?

现在 STR 将被存储在code内存,当你离开的功能, STR 不会坍塌。现在它将打印将我印?

char *getString()
{
    char str[] = "Will I be printed?";    
    return str;
}
int main()
{
    printf("%s", getString());
    getchar();
}

Shouldn't the output be "Will I be printed?" ? Instead, the output is coming out to be some garbage value. Why is it so?

解决方案

char str[] = "Will I be printed?";   

is a local declaration. It is limited with in the function getString(). when you leave the function, str[] will be collapsed.

so you are trying to print the data at it. Obviously you will Garbage value!

To avoid this -

char *str = "Will I be printed?";

Now str will be stored in code memory, when you leave the function, str will not be collapsed. now it will print Will I be printed?

这篇关于什么将是下面的C程序的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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