一、使用sizeof计算普通变量所占的空间
cppreference.com关于sizof operator的文档在这里。下面在64位Windows7系统中进行测试,示例代码如下:
#include <iostream>
using namespace std;
void func(char str[100])
{
cout << sizeof(str) << endl;
}
void main()
{
char charArr[] = "hello";
char *charPtr = charArr;
double d = 3.14;
int n = 1;
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
short sh = 2;
cout
<< "sizeof(charArr) of char charArr[]: " << sizeof(charArr)<< '\n'
<< "sizeof(char): "<< sizeof(char) << '\n'
<< "sizeof(signed char): " << sizeof(signed char) << '\n'
<< "sizeof(unsigned char:): " << sizeof(unsigned char) << '\n'
<< "size of pointer: "<< sizeof(charPtr)<< '\n'
<< "sizeof(*charPtr)->char: " << sizeof(*charPtr) << '\n'
<< "size of double variable: " << sizeof(d) << '\n'
<< "size of int variable: "<< sizeof(n) << '\n'
<< "sizeof(int): "<<sizeof(int) << '\n'
<< "sizeof(int[10]): "<< sizeof(int[10]) << '\n'
<< "sizeof(a): "<< sizeof(a) << '\n'
<< "sizeof(a[10]): "<< sizeof(a[10]) << '\n'
<< "length of int a[10]: "<< sizeof(a)/sizeof(*a) << '\n'// sizeof(a)/sizeof(a[0])或sizeof(int)
<< "sizeof(sh): "<< sizeof(sh)
<<endl;
func(charArr);
cin.get();
}
测试结果截图如下:
分析:
- 程序第11行,charArr为数组名,表示数组。对数组名做sizeof运算得到整个数组占用内存的总大小。因该数组为char类型,strArr的总大小为strlen(charArr)+1 = 6,注意这里不要丢掉"hello"字符串中的字符串结束符'\n'。
- sizeof(char), sizeof(signed char), and sizeof(unsigned char) always return 1.
- 第12行的charPtr为指向char类型数组的指针,对于任何类型的指针,在32位或64位系统中,其大小固定(占用4个字节),即sizeof(指针)的值为4。
- 程序第24行*charPtr为指针指向位置的值,类型为char,即sizeof(*charPtr)等价于sizeof(char),char占1个字节。
- int型数据占4个字节,double占8个字节,char占1个字节,short占2个字节。
- 程序第6行中的str是函数的参数,它在做sizeof运算时被认为是指针。这是因为当我们调用函数func(str)时,由于数组是“传址”的,程序会在栈上分配一个4字节的指针来指向数组,因此结果为4。
二、使用sizeof计算类对象或结构体所占的空间
在64位系统下,观察下面代码的结果:
#include <iostream>
using namespace std;
class A{
public:
int i;
};
class B
{
public:
char ch;
};
class C{
public:
int i;
short sh;
};
class D{
public:
int i;
short sh;
char ch;
};
class E{
int i;
int j;
short sh;
char ch;
char ch2;
};
class F
{
public:
int i;
int j;
int k;
short sh;
char ch;
char ch2;
};
void main(){
cout
<< "sizeof(int) = " << sizeof(int) << '\n'
<< "sizeof(short) = " << sizeof(short) << '\n'
<< "sizeof(char) = " << sizeof(char)
<< endl;
cout
<< "sizeof(A) = " << sizeof(A) << '\n'
<< "sizeof(B) = " << sizeof(B) << '\n'
<< "sizeof(C) = " << sizeof(C) << '\n'
<< "sizeof(D) = " << sizeof(D) << '\n'
<< "sizeof(E) = " << sizeof(E) << '\n'
<< "sizeof(F) = " << sizeof(F)
<< endl;
cin.get();
}
认真看完代码后,你可能认为sizeof(A),sizeof(B)和sizeof(C)的大小不就是类中变量的所占内存的总和吗?其实只答对一半,请记住:各个平台对对存储空间的处理有很大不同,
不要忽略字节对齐(按最大字节数类型对齐)。字节对齐增加了存储的效率,具体细节百度一下你就知道,这里不再赘述。这里仅举一个例子来说明如何计算类对象占用的内存,如下图所示。
因此,该程序的结果为: