C++ sizeof

用法:

 sizeof  + 变量名/ 类型。

  返回结果是size_t(无符号整型), 以字节为单位的该类型内存大小。 

如果是变量名, C内部根据变量名寻找其类型,然后根据类型去计算其大小。 

 

特别注意:

C语言数组名同指针的区别。 

sizeof(数组名): 返回的是数组的字节长度。 

sizeof(指针); 返回的是4. 

 

例子:

#include <iostream>
using namespace std;

typedef struct Test_Other_str
{    char i;
    int j;
    char h[55];
    double k;
} Test_Other;

typedef struct Test_str
{
    char cArr[22];
    int i;
    char cArr1[33];
    double j;
    struct {
        char c1;
        int intArr[4];
        double dArr[6];
    } inner_str;
    char cArr2[44];
    Test_Other* to;
} Test;

int main()
{

    Test* test = (Test*)malloc(sizeof(Test));
    Test_Other* test_other = (Test_Other*)malloc(sizeof(Test_Other));
    test->to = test_other;
    cout << sizeof(test->cArr) << endl;
    cout << sizeof(test->cArr1) << endl;
    cout << sizeof(test->cArr2) << endl;
    cout << sizeof((test->to)->h) << endl;
    free(test_other);
    free(test);

system("pause");


 

C 会根据变量名正确找到类型, 然后根据类型计算其长度。 不用担心字节对齐或者他是不是嵌套结构体中。 

这个实现的很奇妙哈, 不知道C++是怎么实现的。 后续有机会研究下吧。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值