C语言运算符sizeof的反思
1、sizeof操作符的功能:
1. 计算数据类型的大小:
struct Test { int a,b,c,d}; // size == sizeof(int)*4
enum Enum { Monday,Friday,Sunday }; // size == sizeof(int)
union Union { int One, char Ch, double PI }; //size == sizeof(double)
char vec[20] = {0};
char *pChar = NULL;
class MString
{
public:
MString(const char *str = NULL);
MString(const MString & other);
~MString(void);
MString & operator =(const MString & other);
private:
char *m_data;
}; //实现略
sizeof( int/ long/ unsigned/ long long/ double); //内置类型
sizeof(Test); //自定义类型
sizeof(Enum);
sizeof(Union);
sizeof(vec); // 数组的大小 == 20
sizeof(vec[0]); // 第一个元素的大小 == sizeof(char) == 1
sizeof(pChar); // 等于指针在系统中的位数4 32位系统指针大小为4
sizeof('c'); //size == sizeof(char)
sizeof(3); // size == sizeof(int)
sizeof(3.24); // size == sizeof(double)
sizeof(3.14f); // size == sizeof(float)
sizeof(MString) // MString类 类型大小为4 32位系统下
MString str("123456");
MString *pstr = &str;
MString &refstr = str;
sizeof(pstr); // 指针大小 == 4
原本以为可以计算出一个对象在内存中所占的空间,测试发现 这个根本是不符合编程思想的。一个对象的大小是不确定的,其 实质是一个类所需的存储空间是不确定的,所用想用sizeof计算 一个对象的大小时不可能的。它计算出的结构都为4
sizeof(str); // 一个对象变量的大小 size == 4
sizeof(refstr); // 引用类型变量大小 == 4
sizeof(*pstr); // 一个类对象 变量的大小 == 4
以上这些类型都是内存大小确定的,所以可以计算出它们的大小.
struct Area
{
int a:4;
int b:4;
};
struct Area test;
sizeof(test.a); //error 不能用于位域类型计算 invalid application of ‘sizeof’ to a bit-field
总结:sizeof其实质是计算类型的大小,不能计算出自定义类 的对象的内存大小。
2、2.sizeof的用途
1> sizeof常用在动态内存分配中,协助计算内存分配的大小,
因为在不同字长的系统中int,long,short等基础类型的空间大小是不同的,为了保证程序的可移植性,通常用sizeof(int)来确定基础类型的空间大小。
int * pInt = (int *)malloc( sizeof(int)*20 ); //分配20个int空间
2> 计算一个数组中的元素个数 或 数组所占字节数Byte
int count = sizeof(vec) / sizeof(int);
char str[30];
sizeof(str);
3> 不要用sizeof计算除 C风格字符串char str[20]、C++ string str字符串的长度:
应该用 str.strlen();
strlen(str);
计算字符串的长度
4> 不要将sizeof用于除以上外其它的地方,使用在其它地方要慎重!