1,strlen函數(shù)
作用: 用于計(jì)算以空字符'\0'結(jié)尾的字符串的長度,即字符串中的字符個(gè)數(shù),不包括空字符本身。
返回值:strlen返回一個(gè)size_t類型的值,表示字符串中字符的數(shù)量。
注意事項(xiàng):
- strlen 需要在運(yùn)行時(shí)遍歷字符串,直到遇到空字符才停止計(jì)數(shù)。
- 如果字符串沒有以'\0' 結(jié)尾,strlen可能導(dǎo)致未定義的行為。
#include #include
int main() {char str[] = "Hello, World!";size_t length = strlen(str);
printf("Length of the string: %zu\n", length);
return 0;}
2,sizeof運(yùn)算符
作用:用于獲取變量、數(shù)據(jù)類型或數(shù)組在內(nèi)存中占用的字節(jié)數(shù)。
返回值:sizeof返回一個(gè)size_t類型的值,表示操作數(shù)占用的字節(jié)數(shù)。
注意事項(xiàng):
- sizeof是在編譯時(shí)確定的,不需要運(yùn)行時(shí)遍歷數(shù)據(jù)結(jié)構(gòu)。
- 對數(shù)組使用sizeof可以獲取整個(gè)數(shù)組的大小,但對指針使用sizeof只能獲取指針本身的大小。
#include
int main() {char str[] = "Hello, World!";size_t size = sizeof(str);
printf("Size of the array: %zu bytes\n", size);
return 0;}
3,異同點(diǎn)
計(jì)算方式:strlen遍歷字符串直到遇到空字符。sizeof在編譯時(shí)計(jì)算大小。
適用對象:strlen適用于以空字符結(jié)尾的字符串。sizeof適用于變量、數(shù)據(jù)類型或數(shù)組。返回值:strlen返回字符的數(shù)量。sizeof返回字節(jié)數(shù)。字符串長度:strlen計(jì)算字符串長度時(shí)不包括空字符。sizeof計(jì)算字符串長度時(shí)包括空字符。綜上所述,strlen和sizeof在功能和用法上有較大差異,前者主要用于處理字符串的長度,后者用于獲取數(shù)據(jù)結(jié)構(gòu)在內(nèi)存中的大小。
-
字符串
+關(guān)注
關(guān)注
1文章
590瀏覽量
22286 -
函數(shù)
+關(guān)注
關(guān)注
3文章
4381瀏覽量
64879 -
運(yùn)算符
+關(guān)注
關(guān)注
0文章
173瀏覽量
11484
發(fā)布評論請先 登錄
C語言sizeof和strlen的區(qū)別
【武漢華嵌】結(jié)構(gòu)體的sizeof問題
strlen與sizeof區(qū)別
GD32與STM32異同
sizeof和strlen函數(shù)的區(qū)別在哪
字符串函數(shù)strlen的深入研究

sizeof與strlen到底有什么區(qū)別經(jīng)典C語言面試題講解
C語言的sizeof操作符基礎(chǔ)和經(jīng)典問題

C語言模擬實(shí)現(xiàn)strlen的步驟

評論