diff between sizeof and strlen

1. strlen

Returns the length of the C string str.

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).

计算的是字符串以字节为标准的长度

2. sizeof

计算类型或者对象的大小

3. 实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <cstring>
using namespace std;
int main(){
const char* s = "abcgh def";
cout << "strlen(s) " << strlen(s) << endl;
cout << "sizeof(char*) " << sizeof(char *) << endl;
cout << "sizeof(char) " << sizeof(char) << endl;
cout << "sizeof(int) " << sizeof(int) << endl;
cout << "sizeof(double) " << sizeof(double) << endl;
cout << "sizeof(8.0) " << sizeof(8.0) << endl;
cout << "strlen(8.0) " << strlen("8.0") << endl;
union u {
int a;
double d;
char c;
};
cout << "sizeof(u) " << sizeof(u) << endl;
return 0;
}

输出:

strlen(s) 5
sizeof(char*) 8
sizeof(char) 1
sizeof(int) 4
sizeof(double) 8
sizeof(8.0) 8
strlen(8.0) 3
sizeof(u) 8