C/C++ - sizeof操作符详解

C/C++ - sizeof操作符详解

sizeof概述

sizeof是C和C++语言中用于计算数据类型表达式所占用空间大小的一元操作符,是的,它假装得像个函数似的,结果是个操作符。其计算结果单位为字节。

In the programming languages C and C++, the unary operator sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type. ——Wikipedia

sizeof应用

根据作用对象不同,sizeof结果也不相同,具体有以下几种情况。平台相关。

  • 基本类型
    • sizeof(char)为1。
    • 其他基本类型与平台和编译器有关。
  • 指针类型
    • 平台相关,32位机器,指针大小为4字节,因此sizeof作用于指针类型时,结果为4,64位机器为8。
  • 数组
    • sizeof可用于计算静态数组(非malloc动态分配)容量。
  • 联合
    • 对于联合(aggregate)类型,sizeof结果是其最大字节成员的字节数。
  • 结构
    • 对于结构类型,sizeof结果是结构体的总长度,包括任何因字节对齐的填充字节。
  • 枚举
    • 用到的时候Google下再说吧,挺烦人的貌似。

下面是个例子:

#include <stdio.h>

typedef struct test_struct {
    int a;
    char b[4];
} test_struct_t;

void sizeof_test_basic_datatype()
{
    printf("sizeof(char): %lu\n", sizeof(char));
    printf("sizeof(int): %lu\n", sizeof(int));
    printf("sizeof(float): %lu\n", sizeof(float));
    printf("sizeof(double): %lu\n", sizeof(double));
}

void sizeof_test_ext_datatype()
{
    printf("sizeof(test_struct_t): %lu\n", sizeof(test_struct_t));
}

void sizeof_test_array()
{
    char array[100];
    printf("sizeof(array): %lu\n", sizeof(array));
}

#define DATA_TYPE int

void sizeof_test_pointer()
{
    DATA_TYPE *ptr;
    printf("sizeof(ptr): %lu\n", sizeof(ptr));
}

int main(int argc, char *argv[])
{
    /* 编程中最难的技术是命名 */
    sizeof_test_basic_datatype();
    sizeof_test_ext_datatype();
    sizeof_test_array();
    sizeof_test_pointer();

    return 0;
}

sizeof补充说明

  • 函数调用时如果用数组作为参数,那么形参为指针,此时如果函数中对数组指针做sizeof操作,那么求得的结果为指针大小,而非原数组的容量。
  • 如果sizeof的操作数是一个表达式的话,这个表达式时不会被计算的。下面是一个比较无聊的例子。
void sizeof_test_expression()
{
    int i;
    i = 10;
    printf("%d\n", i);
    printf("sizeof(i++): %lu\n", sizeof(i++));
    printf("%d\n", i);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值