📅  最后修改于: 2023-12-03 15:20:09.084000             🧑  作者: Mango
在C++中,sizeof是一个关键字,常用于计算数据类型或表达式的字节大小。返回值的类型是size_t。
sizeof (type)
sizeof expression
type
- 数据类型
expression
- 表达式
返回值 - size_t类型的整数值,表示表达式或类型的字节大小。
#include <iostream>
using std::cout;
using std::endl;
int main() {
cout << "The size of int is " << sizeof(int) << " bytes" << endl;
cout << "The size of float is " << sizeof(float) << " bytes" << endl;
cout << "The size of char is " << sizeof(char) << " byte" << endl;
return 0;
}
程序输出:
The size of int is 4 bytes
The size of float is 4 bytes
The size of char is 1 byte
#include <iostream>
using std::cout;
using std::endl;
int main() {
int arr[5];
cout << "The size of arr in bytes is " << sizeof(arr) << endl;
cout << "The number of elements in arr is " << sizeof(arr)/sizeof(arr[0]) << endl;
return 0;
}
程序输出:
The size of arr in bytes is 20
The number of elements in arr is 5
#include <iostream>
using std::cout;
using std::endl;
struct Person {
int age;
float height;
char gender;
};
int main() {
cout << "The size of Person struct is " << sizeof(Person) << " bytes" << endl;
return 0;
}
程序输出:
The size of Person struct is 9 bytes