sizeof
sizeof运算符用于获取数据类型、变量或表达式所占用的内存大小(以字节为单位)。
获取类型长度
size_t sizeof_datatype = sizeof(type);获取变量长度
size_t sizeof_variable = sizeof(variable);示例用法:
#include <iostream>
using namespace std;
int main()
{
cout<<sizeof(int)<<endl;//4
cout<<sizeof(char)<<endl;//1
cout<<sizeof(double)<<endl;//8
return 0;
}#include <iostream>
using namespace std;
int main()
{
int x;
size_t x_size = sizeof(x);
cout<<x_size<<endl;//4
int buffer[100];
size_t buffer_size = sizeof(buffer);
cout<<buffer_size<<endl;//400
size_t buffer_size2 = sizeof(buffer[0]);
cout<<buffer_size2<<endl;//4
return 0;
}#include <iostream>
using namespace std;
int main()
{
size_t expr_size = sizeof(1 + 2.0);
cout<< expr_size<<endl;//8
return 0;
}#include <iostream>
using namespace std;
int main()
{
int arr[100];
int n=sizeof(arr) / sizeof(arr[0]);//存储arr的数组大小
return 0;
}strlen用于计算一个以null终止字符数组(即C字符串)的长度,也就是字符串中字符的数量,但不包括字符串结尾的null字符 (
'\0'),即hello长度就是5.
使用该函数需要导入库函数
#include <string.h>示例
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "Hello";
size_t length = strlen(str);
printf("字符串 \"%s\" 的长度是 %zu\n", str, length);//字符串 "Hello" 的长度是 5
return 0;
}