基本含义
sizeof()实际上是一个单目运算符,计算括号内对象的内存大小。
strlen()是求括号内字符串、以括号内地址为首址的字符串为首址,下一个“\0”为结束标志的长度。
strlen()以“\0”为结束标志
尤其是在没有指定大小的字符型数组中,以“string”方式赋值给字符数组时会自动在末尾加入“\0”,以‘a’单个字符方式赋值时不会在末尾加上“\0”,所以:
例子1
#include <iostream>
using namespace std;
int main() {
char a0[] = { "hello" };
char a1[] = { "hel\0lo" };
char a[12] = { "hel\0lo" };
char b0[] = { 'h','e','l','l','o' };//警告:可能没有为字符串‘b0’添加字符串零终止符
char b1[] = { 'h','e','l','l','o', '\0' };
char b[12] = { 'h','e','l','l','o','\0' };
cout <<"a0:\t" << "[strlen] " << strlen(a0) << "\t[sizeof] " << sizeof(a0) << endl;
cout << "a1:\t" << "[strlen] " << strlen(a1) << "\t[sizeof] " << sizeof(a1) << endl;
cout << "a:\t" << "[strlen] " << strlen(a) << "\t[sizeof] " << sizeof(a) << endl;
cout << "b0:\t" << "[strlen] " << strlen(b0) << "\t[sizeof] " << sizeof(b0) << endl;
cout << "b1:\t" << "[strlen] " << strlen(b1) << "\t[sizeof] " << sizeof(b1) << endl;
cout << "b:\t" << "[strlen] " << strlen(b) << "\t[sizeof] " << sizeof(b) << endl;
return 0;
}
运行结果:
a0: [strlen] 5 [sizeof] 6
a1: [strlen] 3 [sizeof] 7
a: [strlen] 3 [sizeof] 12
b0: [strlen] 37 [sizeof] 5
b1: [strlen] 5 [sizeof] 6
b: [strlen] 5 [sizeof] 12
另外(转义字符相关)
char c[] = { "ab\\\0c" };
cout<< "[strlen] " << strlen(c) << "\t[sizeof] " << sizeof(c) << endl;
char d[] = { "abc" };
cout << "[strlen] " << strlen(d) << "\t[sizeof] " << sizeof(d) << endl;
运行结果:
[strlen] 3 [sizeof] 6
[strlen] 3 [sizeof] 4
例子2
#include <iostream>
using namespace std;
int main() {
char c[] = { "ab\\\\0c" };
cout<< "[strlen] " << strlen(c) << "\t[sizeof] " << sizeof(c) << endl;
for (int i = 0; i < sizeof(c); i++) {
cout << "c[" << i << "] = " << c[i] << "\t";
}
cout << endl;
char c1[] = { "ab\\\0c" };
cout << "[strlen] " << strlen(c1) << "\t[sizeof] " << sizeof(c1) << endl;
for (int i = 0; i < sizeof(c1); i++) {
cout << "c1[" << i << "] = " << c1[i] << "\t";
}
cout << endl;
char d[] = { "abc" };
cout << "[strlen] " << strlen(d) << "\t[sizeof] " << sizeof(d) << endl;
return 0;
}
运行结果:
[strlen] 6 [sizeof] 7
c[0] = a c[1] = b c[2] = \ c[3] = \ c[4] = 0 c[5] = c c[6] =
[strlen] 3 [sizeof] 6
c1[0] = a c1[1] = b c1[2] = \ c1[3] = c1[4] = c c1[5] =
[strlen] 3 [sizeof] 4