posts - 15, comments - 8, trackbacks - 0, articles - 2

关于sizeof

Posted on 2010-08-03 21:06 小天狼星 阅读(436) 评论(0)  编辑 收藏 引用

       前段时间接连到公司面试,其中这些公司包括什么华为,文思创新以及其他一些不出名的或忘了叫什么名字的垃圾公司,跑了不少路,做了不少的笔试题,感觉关于sizeof的运算相关的题目较多,自己将题做的一片糊涂,回来后亲自写了实验来验证。先帖代码:

#include <iostream>
using namespace std;
struct t
{
    
char l;
    
float a;
    
int b[3];
}
;
void func(char ch[100])
{
    cout 
<< "sizeof ch :" <<sizeof(ch) <<endl;
}


void main()
{
    
char * s = "hello";
        char c ;
    
char d[]  = "hello";
    
char r[100];
    func(r);
    cout 
<< “sizeof s :”<<sizeof(s)<<endl

               <<"sizeof c" <<sizeof(c)<<endl

                
<< "sizeof d[] = hello : " << sizeof(d) <<endl 

           
<< "sizeof t :"<<sizeof(t) <<endl 

               
<<"sizeof char r[100] : "<< sizeof(r) <<endl;
}


再帖转载来的6条理论:

sizeof操作符的结果类型是size_t,它在头文件中typedef为unsigned int类型。该类型保证能容纳实现所建立的最大对象的字节大小。

   1、若操作数具有类型char、unsigned char或signed char,其结果等于1。

         ANSI C正式规定字符类型为1字节。

   2、int、unsigned int 、short int、unsigned short 、long int 、unsigned long 、float、double、long double类型的sizeof 在ANSI C中没有具体规定,大小依赖于实现,一般可能分别为4、4、2、2、4、4、4、8、10。
               
               sizeof(c) = 1;

   3、当操作数是指针时,sizeof依赖于编译器。例如Microsoft C/C++7.0中,near类指针字节数为2,far、huge类指针字节数为4。一般Unix的指针字节数为4。

               对于示例程序中的sizeof s,根据第3条,s是个字符串的指针,输出为   sizeof s :4


   4、当操作数具有数组类型时,其结果是数组的总字节数。

                对于sizeof d[] ,根据第4条,d是数组类型,返回的是数组的字节数再加上末尾的null一字节,sizeof d[] = hello : 6


   5、联合类型操作数的sizeof是其最大字节成员的字节数。结构类型操作数的sizeof是这种类型对象的总字节数,包括任何垫补在内。

          让我们看如下结构:

          struct {char b; double x;} a;

          在某些机器上sizeof(a)=12,而一般sizeof(char)+ sizeof(double)=9。

          这是因为编译器在考虑对齐问题时,在结构中插入空位以控制各成员对象的地址对齐。如double类型的结构成员x要放在被4整除的地址。
                对于sizeof t ,对齐后t的大小为20故输出结果为sizeof t :20


   6、如果操作数是函数中的数组形参或函数类型的形参,sizeof给出其指针的大小。
                 sizeof ch :4


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理