一道简单的C语言题

看一下下面的一段简单的C语言程序,它的输出结果是多少:

 

#include<stdio.h>
#include<string.h>

int main()
{
    int a=257;
    char buf[5] = "aaaa";
    strcpy(buf ,(char*)&a);
    printf("%d\n",strlen(buf));
    return 0;
}

 

 

分析:257用二进制表示为:000100000001,用16进制表示为:0x00000101。buf在内存中的应该以"aaaa\0"来存储。先画一下变量a和buf的内存模型图:

 

(char*)&a:即把a转换成char类型的指针,此时a指向整形的四个字节中的第一个字节,如图:

我们在来看一下strcpy(buf,(char*)&a);这句话,看一下strcpy的含义:

 

strcpy

char * strcpy ( char * destination, const char * source );

Copy string

Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).

To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.

 

即:将a指向的内容依次拷贝到buf指向的内容中去,a指向的内容遇到空字符,然后停止。依次只有当a遇到'00'的时候就会停止了,只会将'01'/'01'/'00'依次拷贝到buf[0]/buf[1]/buf[2]中去,buf就会变成这样:

我们增加一行代码来打印buf中的内容:

 

printf("%d %d %d %d\n",(int)buf[0],(int)buf[1],(int)buf[2],(int)buf[3]);


其中97就是字符'a'的ASCII码十进制表示。

 

 

然后回到题目中:strlen(buf)很明显结果为2,因为buf[2]='00',strlen遇到它就停止计算,依次buf[2]前只有两个字符。差不多了,可以得出结论输出为2了。但是确定为2吗?

当然不是,当画出a的内存模型的时候我默认的是小段存储,关于大小端存储的原理有很多博文讲到,在此不多说,只是提供一个判断机器是大小段存储的测试程序:

 

#include<stdio.h>

void byteorder()
{
    union
    {
        short value;
        char union_bytes[ sizeof(short) ];
    }test;    
    test.value = 0x0102;
    if( (test.union_bytes[0] == 1)&&(test.union_bytes[1]==2 ) ) 
    {
        printf("big endian\n");   
    }
    else if( (test.union_bytes[0] == 2)&&(test.union_bytes[1]==1 ) )
    {
        printf("little endian\n");
    }
    else
    {
        printf("unknown...\n")    ;
    }
}

int main()
{
    byteorder();
    return 0;    
}


我们一般用的机子都是小段存储。如果对于大段存储的机器,那么得到的结果strlen(buf)就是0了,至于为什么,请思考。

 

 

 

注明出处:http://blog.csdn.net/lavorange/article/details/21872741

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值