sizeof()函数用法与举例

sizeof()函数用法与举例

1. sizeof(type)
    sizeof(char)=1; sizeof(short)=2; sizeof(int)=4;   // sizeof(int)=2 is C
    sizeof(void *)=4;

    Be careful about character variable and character constant in C:

                 ch = 'a'; sizeof(ch)=1; sizeof('a')=2;  // 'a' is of type int
2. sizeof(variable)
    e.g.    int a;       // sizeof(a)=4;
   Be careful when dealing with the array or the pointer:
    e.g.
    char ch1[]="Hello";     // sizeof(ch1)=6; but strlen(ch1)=5;
    char *ch2="World!";     // sizeof(ch2)=4;
   When dealing with struct variables, the return value of sizeof() may be larger than you expected because of the bytes alignment.
    e.g.
    struct stru1 {int a; char c;} st1;  //sizeof(struct stru1)=sizeof(st1)=8;
    struct stru2 {int a; int b;} st2;    //sizeof(struct stru2)=sizeof(st2)=8;

3. The macro offsetof() defined in <stddef.h>
    We can use offsetof(struct stru1, b) to calculate the offset of domain c in struct stru1. Or we can use the following expression to access (assume struct stru1  *pst1)
    *(int *)((char *)pst1 + offsetof(struct stru1, b)) = value;

 

Output:

sizeof(short) = 2, sizeof(a) = 2.
sizeof(short*) = 4, sizeof(*pa) = 4.
sizeof(char) = 1, sizeof(ch) = 1.
sizeof(char*) = 4, sizeof(pch) = 4.
sizeof(ch1) = 6, sizeof(*ch2) = 1, sizeof(ch2) = 4.
sizeof(struct stru1) = 8, sizeof(st1) = 8.
sizeof(struct stru2) = 8, sizeof(st2) = 8.
Press any key to continue . . .

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值