记住以下几个结论:
1.unsigned影响的只是最高位bit的意义(正负),数据长度不会被改变的。所以sizeof(unsigned
2.自定义类型的sizeof取值等同于它的类型原形。如typedef short WORD;sizeof(short) == sizeof(WORD)。
3.对函数使用sizeof,在编译阶段会被函数返回值的类型取代。如:
4.只要是指针,大小就是4。如:cout < <sizeof(string*) < <endl;
5.数组的大小是各维数的乘积*数组元素所属类型的大小。如:
6.字符串的sizeof和strlen的区别(见下列示例)。
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#include <iostream>
#include <string>
#include <cstddef>
using namespace std;
int main_test5()
{
size_t ia; //返回值的类型是 size_t 这是一种与机器相关的typedef定义,在cstddef头文件中
ia = sizeof ( ia ); // ok
ia = sizeof ia; // ok
// ia = sizeof int; // 错误
ia = sizeof ( int ); // ok
int *pi = new int [ 12 ];
cout << "pi: " << sizeof ( pi ) //4个字节:指针大小
<< " *pi: " << sizeof ( *pi ) //4个字节:数组的第一个元素为int型
<< endl;
// 一个 string 的大小与它所指的字符串的长度无关
string st1( "foobar" );
string st2( "a mighty oak" );
string *ps = &st1;
cout << "st1: " << sizeof ( st1 ) //32个字节
<< " st2: " << sizeof ( st2 ) //32个字节
<< " ps: " << sizeof ( ps ) //4个字节:指针大小
<< " *ps: " << sizeof ( *ps ) //32个字节,*ps表示字符串内容,相当于sizeof(string)
<< endl;
cout << "short :\t" << sizeof ( short ) << endl; //2个字节
cout << "short* :\t" << sizeof ( short *) << endl; //4个字节
cout << "short& :\t" << sizeof ( short &) << endl; //2个字节
cout << "short[3] :\t" << sizeof ( short [3]) << endl; // 6个字节 = 每个元素大小2 * 共3个元素
cout << "short :\t" << sizeof ( int ) << endl; //4个字节
cout << "short* :\t" << sizeof (unsigned int ) << endl; //4个字节
char a[] "abcdef " ;
int b[20]
char c[2][3] "a" , "b" };
cout << sizeof (a) <<endl; //
cout << sizeof (b) <<endl; //
cout << sizeof (c) <<endl; //
//字符串的sizeof和strlen的区别
char aa[] "abcdef " ; //末尾是空格
char bb[20] "abcdef " ; //末尾是空格
string "abcdef " ; //末尾是空格
cout << strlen (aa) <<endl; //
cout << sizeof (aa) <<endl; //
cout << strlen (bb) <<endl; //
cout << sizeof (bb) <<endl; //
cout << sizeof (s) <<endl; //
//错误: 不能将参数 1 从“std::string”转换为“const char *”
//cout <<strlen(s) <<endl;
aa[1] '\0 ' ;
cout << strlen (aa) <<endl; //
cout << sizeof (aa) <<endl; //
return 0;
}
|
一道面试题:
题目是要求输出:TrendMicroSoftUSCN ,然后要求修改程序,使程序能输出以上结果。代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include <iostream>
#include <string>
using namespace std;
int main( int argc, char *
{
string "Trend " , "Micro " , "soft " };
string new string[2];
p[0]= "US " ;
p[1]= "CN " ;
cout < < sizeof (strArr1) < <endl;
cout < < sizeof (p) < <endl;
cout < < sizeof (string) < <endl;
for ( int i=0;i < sizeof (strArr1)/ sizeof (string);i++)
cout < <strArr1[i];
for (i=0;i < sizeof (p)/ sizeof (string);i++)
cout < <p[i];
cout < <endl;
}
|
答案:
如果将
for(i=0;i <sizeof(p)/sizeof(string);i++)
改为
for(i=0;i <sizeof(p)*2/sizeof(string);i++)
答案也是不对的,sizeof(p)只是指针大小为4,要想求出数组p指向数组的成员个数,应该为
for(i=0;i <sizeof(*p)*2/sizeof(string);i++)
为什么?指针p指向数组,则*p就是指向数组中的成员了,成员的类型是什么,string型,ok那么sizeof(*p)为32,乘以2才是整个数组的大小。