由strlen和sizeof引起的思考
阿新 • • 發佈:2022-06-01
strlen 函式
std::size_t strlen( const char* str );
- 返回給定字串的長度,即從
str
指向的首元素到以首個空字元\0
結尾的字串的字元數,注意:不包含\0
。
sizeof 運算子
- 查詢物件或型別的大小。即求資料型別所佔的空間大小。
語法
- sizeof(
表示式(expression)或型別(type)
),獲得表示式(expression)或型別(type)
的物件表示的位元組數。 - sizeof
表示式(expression)
,獲得表示式(expression)
的型別的物件表示的位元組數。
sizeof a; //正確
sizeof int;//錯誤
思考
1
- strlen不計入
\0
const char str[] = "How";
std::cout << "without null character: " << std::strlen(str) << '\n'
<< "with null character: " << sizeof str << '\n';
/*
without null character: 3
with null character: 4
*/
2
- str與str2不同。str為維度為4的陣列,只是初始化時未顯式定義長度;
- str2為指標,所有
sizeof str2
實際是計算指標所佔的空間大小,在64位系統下為8個位元組。
const char str[] = "How"; const char* str2 = "How"; std::cout << "strlen of str: " << std::strlen(str) << '\n' << "strlen of str2: " << std::strlen(str2) << '\n'; std::cout << "sizeof of str: " << sizeof str << '\n' << "sizeof of str2: " << sizeof str2 << '\n'; /* strlen of str: 3 strlen of str2: 3 sizeof of str: 4 sizeof of str2: 8 */
3
- strlen統計字串實際長度,sizeof查詢分配空間大小。
-
char str3[10]="How";
只能加9個字元,因為還要留一個給\0
.
char str3[10]="How";
std::cout << "strlen of str3: " << std::strlen(str3) << '\n'
<< "sizeof of str3: " << sizeof(str3) << '\n';
/*
strlen of str3: 3
sizeof of str3: 10
*/