sizeof :运算符,返回类型或数据对象的长度,单位为字节。
用法:
- 数据类型:sizeof(char):返回对应长度。
- 普通变量:sizeof(a):返回对应长度。
- 数组:sizeof(数组名):返回整个数组所占字节数。sizeof(数组元素):返回元素长度。
- 指针:sizeof(p):返回指针长度。本系统均为8字节。
void test_sizeof()
{
cout << sizeof(char) << endl; //1
cout << sizeof(int) << endl; //4
cout << sizeof(double) << endl; //8
int a = 3;
int arr[5] = {4, 6};
int arr2[] = {7, 8, 9};
cout << sizeof(a) << endl; //4
cout << sizeof(arr[1]) << endl; //4
cout << sizeof(arr) << endl; //20
cout << sizeof(arr2) << endl; //12
int *p = arr;
int *q = &arr[1];
cout << p << endl; //0x65fdb0
cout << *p << endl; //4
cout << q << endl; //0x65fdb4
cout << *q << endl; //6
cout << sizeof(p) << endl; //8
cout << sizeof(*p) << endl; //4
cout << sizeof(q) << endl; //8
cout << sizeof(*q) << endl; //4
char *cptr;
short *sptr;
int *ptr;
double *dptr;
cout << sizeof(cptr) << endl; //8
cout << sizeof(*cptr) << endl; //1
cout << sizeof(sptr) << endl; //8
cout << sizeof(*sptr) << endl; //2
cout << sizeof(ptr) << endl; //8
cout << sizeof(*ptr) << endl; //4
cout << sizeof(dptr) << endl; //8
cout << sizeof(*dptr) << endl; //8
}
- 用于字符串char数组:sizeof 返回值与存储内容无关,返回数组大小。
const int Size = 10;
char name[Size];
cin >> name; // fan
cout << sizeof(name) << endl; //10
cout << strlen(name) << endl; //3
- sizeof 指出整个数组的长度:10字节。
- strlen 返回存储在数组中的字符串的长度,不包含结尾的空字符 '\0' 。
const int Size = 10;
char name[Size];
cin >> name; // 12345678 9
cout << sizeof(name) << endl; //10
cout << strlen(name) << endl; //8
const int Size = 10;
char name[Size];
cin >> name; // 123456789101112
cout << sizeof(name) << endl; //10
cout << strlen(name) << endl; //15
sizeof 与 strlen 区别:
- sizeof 是操作符, strlen 是库函数,存放在<cstring>头文件中。
- sizeof 参数可以是类型或变量,strlen 以字符串为参数,接受char数组。
- sizeof 在编译时已知,strlen 在运行时计算。
- sizeof 计算内存大小,与具体内容无关,strlen 计算字符串实际长度,遇到空字符结束,不包含结尾空字符 ‘\0’ 。