C莫名其妙题目

有时候会遇到一些莫名其妙的题目,输出一些莫名其妙的结果,但是其中都有有道理的,需要好好理解。

#include<stdio.h>
int main()
{
    int  a='abc';
    printf("%s\n",&a);
    //printf(&a);

}

在window XP系统,C-Free中执行

编译时有两个警告,最后输出结果是cba。

解释:

int a='abc';
编译器会将'abc'扩展为int,它的值为
6382179 即0x00616263
而intel int内存的实际存储格式是低位在前,所以实际a指向的内容为
0x63626100
如果按字串输出,正好是
cba
且正好是以\0结尾
C99标准中有说到:

ISO/IEC 9899:1999 (E)
§6.4.4.4
Semantics
10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer.
The value of an integer character constant containing more than one character (e.g.,'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int

还有c++中多字节字符常量( multicharacter literal),其值都是实现来定义的


修改下:
#include<stdio.h>
int main()
{
    int  a='abcde';
    printf("%s\n",&a);
    //printf(&a);

}

结果输出为edcb?“

a被丢弃了,因为超出了int的范围,int只会保持最后的四个数值,前面的都会丢弃掉,因此可以正常输出edcb,然后继续输出知道找到结束符停止。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值