sizeof用法总结

sizeof的用法总结


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
//在64为机器上进行测试,linux
#include <iostream>
#include <string>

using namespace std;

int main(){
#include <iostream>
#include <string>

using namespace std;

int main(){
char *str = NULL;
string s;
cout<<sizeof(char)<<endl; //1

cout<<sizeof(int)<<endl; //4
cout<<sizeof(short)<<endl; //2
cout<<sizeof(double)<<endl; //8
cout<<sizeof(long long)<<endl; //8
cout<<sizeof(str)<<endl; //8
cout<<sizeof(s)<<endl; //8

//指针的都为8
cout<<sizeof (char*)<<endl; //8
cout<<sizeof(int *)<<endl; //8

cout<<"About sizeof"<<endl;
//声明一个二维数组,数组中存放的是一维指针
int* (*a)[3][6];
cout<<sizeof(a)<<endl; // 8 a为指针
cout<<sizeof(*a)<<endl; // 144 *a为一个有3*6个指针元素的数组(3*6*(sizeof(int*))=144)
cout<<sizeof(**a)<<endl; // 48 **a为数组一维的6个指针
cout<<sizeof(***a)<<endl; // 8 ***a为一维的第一个指针
cout<<sizeof(****a)<<endl; // 4 ****a为一个int变量



cout<<"About sizeof"<<endl;
//声明一个二维数组,数组中存放的是指针的指针
int** b[3][6];
cout<<sizeof(b)<<endl; //144
cout<<sizeof(*b)<<endl; //48 //一维数组
cout<<sizeof(**b)<<endl; //8 //数组中的元素,指针的指针
cout<<sizeof(***b)<<endl; //8
cout<<sizeof(****b)<<endl; //4

//二维数组,数组中的元素为指针
int* p[3][6];
cout<< sizeof(p)<<endl; //144
cout<<sizeof(*p)<<endl; //48
cout<<sizeof(**p)<<endl; //8
cout<<sizeof(***p)<<endl; //4

cout<<"matrix:"<<endl;
//内存不是连续的,先申请一维,再申请二维
int q[2][3]={1,2,3,4,5,6};
cout<< sizeof(q)<<endl; //24(2*3*4 = 24)
cout<<sizeof(*q)<<endl; //12
cout<<sizeof(**q)<<endl; //4

return 0;
}
}

int* (\a)[3][6];
(\
a) 是一个指向int指针构成的二维数组,
a就是一个指针,sizeof(a) = sizeof(int *) = 8;
(*a) = 3*6*sizeof(int*) = 144;
(**a)是int*[6]类型的,故为6*sizeof(int *) = 48;
(***a)为int *,为8
(****a)为int,为4