一道简单的C语言题

时间:2023-02-10 15:05:12

看一下下面的一段简单的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的内存模型图:

一道简单的C语言题


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

我们在来看一下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就会变成这样:

一道简单的C语言题

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

printf("%d %d %d %d\n",(int)buf[0],(int)buf[1],(int)buf[2],(int)buf[3]);
一道简单的C语言题
其中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