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。
- 平台相关,32位机器,指针大小为4字节,因此
- 数组
sizeof
可用于计算静态数组(非malloc
动态分配)容量。
- 联合
- 对于联合(aggregate)类型,
sizeof
结果是其最大字节成员的字节数。
- 对于联合(aggregate)类型,
- 结构
- 对于结构类型,
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);
}