siseof 操作符的作用是返回一个对象或类型名的字节长度它有以下三种形式
sizeof (type name );
sizeof ( object );
sizeof object;
A:
string s="testing";
int n=sizeof(s); // n=16
int m=sizeof(string);// m=16
int k=s.lenmgth(); // k=7
int i=sizeof(s.c_str());//i=8;
sizeof(s)等于string类的大小,sizeof(s.c_str())得到的是与 字符串长度
B:
string s="testing/0";
int n=sizeof(s); // n=16, 如果string s="1254235sdgsdghsdhgsdhsdhdsfhsdf"sizeof(s)任然等于16
int k=s.length(); // k=7
从A,B可以看出对于string变量,sizeof(变量)等于sizeof(string)=16,s.length(); 是取到字符结束符/0为止的字符串长度
C:
char a[]="testing";
n=sizeof(a); // n=8
k=strlen(a); //k=7
D: char a[]="testing/0";
n=sizeof(a);//n=9
k=strlen(a);//k=7
E: char a[10]="testing/0";
n=sizeof(a); //a=10
k=strlen(a); //k=7
//从C,D可以看出对于不定长的数组char a[]其真正的size长度取决于其初始化的字符长度(包括自负结束符在内),D:中的字符串实际为
testing/0/0; E 呢则是指定了数组长度因此sizeof(a)=10*sizeof(char);
F: CString sT="testing/0";
n=sizeof(sT); //n=4
n=sizeof(CString); //n=4
k=strlen(sT); // k=7
int m=sT.GetAllocLength(); // k=7
int j=sT.GetLength(); // k=7
通过ABCDEF的对比我们可以总结非数组情况下sizeof(变量名)等于sizeof变量类型)
2.指针与静态数组的sizeof操作
指针均可看为变量类型的一种。所有指针变量的
sizeof 操作结果均为4。
注意
:int
*p; sizeof(p)=4;
但sizeof(*p)相当于sizeof(int);
对
于静态数组,sizeof可直接计算数组大小;
例:int a[10];char b[]="hello";
sizeof(a)
等于4*10=40;
sizeof(b)等于6;
注意
:数组做型参
时,数组名称当作指针使用!!
void fun(char p[])
{sizeof(p)
等于4}