IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    弄懂sizeof

    Fish (fsh267@gmail.com)发表于 2014-02-24 00:00:00
    love 0

    #sizeof及其用法

    ###1. sizeof在msdn上的定义如下:

    The sizeof keyword gives the amount of storage, in bytes, associted with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

    sizeof 不是函数, 而是 C 语言数据类型关键字.

    ###2. sizeof 用法如下:

    • sizeof(object)
    • sizeof(typename)

    可以对对象使用 sizeof, 也可以对类型使用. sizeof i OR sizeof(int).

    通过sizeof i 更能看出, sizeof 不是函数. 不过, 在使用的时候, 最好都加上括号. 看看在64位机子上, 各个数据类型的大小:

    cout << sizeof(int) << endl;            //4
    cout << sizeof(unsigned int) << endl;   //4
    cout << sizeof(unsigned) << endl;       //4
    cout << sizeof(short int) << endl;      //2
    cout << sizeof(char) << endl;           //1
    cout << sizeof(string *) << endl;       //8
    cout << sizeof(void *) << endl;         //8 
    cout << sizeof(char *) << endl;         //8
    cout << sizeof(int *) << endl;          //8

    可以看出, 指针的不管类型, 都是8, 32位机一般都是4.

    ###3. 数组大小问题 看看下面的函数

    char a[] = "abcdefg";
    int b[13] = {
        1, 2
    };
    char c[2][8] = {
        "aa", "bb"
    };
    cout << sizeof(a) << endl;  //8
    cout << sizeof(b) << endl;  //52
    cout << sizeof(c) << endl;  //16

    记住, 数组的大小就是在被编译是给的空间 ###4. 注意 sizeof 对象是数组和指针的区别 当 sizeof 对象是数组时, 返回的是数组的大小, 对象是指针时, 返回的是指针的大小. 注意, 当数组名作为实参传入函数时, 会自动转换为指针类型, 如下:

    void foo(int a[]){
        cout << sizeof(a) << endl;
    }
    int main()
    {
        int a[] = {1, 2, 3, 4, 5};
        int *p = a;
        cout << sizeof(a) << endl;  //20
        cout << sizeof(p) << endl;  //8
        foo(a);                     //8
        return 0;
    }

    strlen 和 sizeof 比较

    这个问题, 在面试上经常碰到. strlen 是从开始到出现’\0’为止, 中间字符的个数, 是在运行阶段执行的, 而 sizeof 是得到数据的大小, 和 strlen 相比, 是得到字符串的容量.如下:

    char a[] = "abcdef";
    char b[22] = "abcdef";
    string s = "abcdefg";
    
    cout << strlen(a) << endl;  //6
    cout << strlen(b) << endl;  //6
    cout << strlen(s) << endl;  //error
    
    cout << sizeof(a) << endl;  //7
    cout << sizeof(b) << endl;  //22
    cout << sizeof(s) << endl;  //8

    还有, strlen 是一个函数, 得有括号. 在 C++ 中, string 是一个类, 上面函数中的 s 就是一个对象, 因此, sizeof(s) 表示的是类 string 的大小.

    strlen(s) 是错误的, 因为 strlen 的参数是一个字符指针, 如果想得到字符串的长度, 应该使用 sizeof(s.c_str()), string 的成员函数c_str() 返回的是字符串的首地址.

    struct 的结构对其问题

    字节对其也称为字节填充, 他是 C++ 编辑器的一种技术手段, 主要是为了在空间与复杂度上达到平衡. 一般而言, struct 的 sizeof 是所有成员对齐后长度相加, 而 union 的 sizeof 是取最大的成员长度 . 看下面两个例子:

    struct test{
        char x1;
        short x2;
        float x3;
        char x4;
    };
    cout << sizeof(test) << endl;   //12
    
    strcut test2{
        short d;
        int a;
        short b;
    };
    cout << sizeof(test2) << endl;  //12 

    我的理解是, 上面的成员按 4 对齐, 1 + 2( 补齐 ) + 4 + 1( 补齐 ) = 12, 2( 补齐 ) + 4 + 2( 补齐 ) = 12; 如果最大成员为 8, 则按 8 补齐.

    #END



沪ICP备19023445号-2号
友情链接