以下是 sizeof 和 strlen 的使用示例:
#include <iostream>
int main() {
int num = 10;
std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl; // 输出 "Size of int: 4 bytes"
std::cout << "Size of num: " << sizeof(num) << " bytes" << std::endl; // 输出 "Size of num: 4 bytes"
char str[] = "Hello";
std::cout << "Size of str: " << sizeof(str) << " bytes" << std::endl; // 输出 "Size of str: 6 bytes"
return 0;
}
sizeof 可以直接计算类型或变量所占的字节数,无需额外的参数,可以用于基本类型、自定义类型、数组等。
#include <iostream>
#include <cstring>
int main() {
const char* str = "Hello, World!";
size_t length = strlen(str);
std::cout << "Length of str: " << length << std::endl; // 输出 "Length of str: 13"
return 0;
}
strlen 需要以 null 结尾的字符数组(字符串)作为参数,返回字符串的长度,即不包括 null 终止符 \0 的字符个数。