关于strlen和sizeof的区别
strlen 和 sizeof 自己一直没有注意去研究,一直迷惑, 凡事还需巨细靡遗啊!巨细靡遗! 巨细靡遗!
[strlen]
c++ reference 中说:
The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
意思是: c 的字符串类型的长度是由空字符决定的。 一个c字符串类型的长度是从字符串开始到空字符之间的字符数量(不包含空的结束符)。
strlen是函数, 运行时,计算实际的长度。
sizeof
sizeof 不是函数,是c语言中判断数据类型长度的关键字, 属于操作符。返回值类型为size_t类型的值。 而size_t 在32位系统是4字节, 在64系统是8个字节。 这样利用该类型可以增强程序的可移植性。大部分程序在编译的时候就把sizeof计算好了
直接上程序更清晰:
举例:
const char* str = "hello, world"; // 以字符串形式出现的,编译器都会为该字符串自动添加一个'\0'结束符, 如在代码中写"abc", 那么编译器帮你存储为"abc\0"
int len = strlen(str); // 返回的是12,
size_t size = sizeof(str); // str 是一个指针,指针存储的是一个变量的地址,与系统有关,一般32位的系统,内存地址就是0~2^32, 内存地址占用4个字节; 如果是64位系统,就是8个字节。
char mystr[100] = "hello, world";
int len1 = strlen(mystr); // 12
size_t size = sizeof(mystr); // 100
char str2[3] = "abc"; // 编译会报错, 因为编译器会自动在"abc"后追加一个'\0', 所以超出了str2的长度, 改为 char str2[4] = "abc";就对了
char str3[3] = {'a', 'b', 'c'};
int len3 = strlen(str3); // 这里的结果会不确定,因为strlen搜寻结尾的'\0'
int size4 = sizeof(str3)/sizeof(char) // 3
int calc(char a[]) {
cout << "size of arr is " << sizeof(a)/sizeof(char) << endl;
cout << "len of arr is " << strlen(a) << endl;
}
char str5[100] = "hello, world!"
calc(str5); // size str5 是4, 编译时,只会将a解释为指针
// 12, 运行时,根据传入的字符串,计算长度。