C語言入門篇--sizeof與strlen基礎(chǔ)理論
1.sizeof
(1)若求字符串占據(jù) 空間 的大小,包括字符串結(jié)尾處默認(rèn)的'\0'。
(2)若所求不是字符串的大小,求的是數(shù)組、類型等的大小,不用考慮'\0',因?yàn)椴皇亲址诮Y(jié)尾處無默認(rèn)的'\0'。
(3)若明顯出現(xiàn)'\0',則統(tǒng)計(jì)。
(4)返回一個(gè)變量或者類型的大?。ㄒ宰止?jié)為單位)
2.strlen
求字符串內(nèi)容的大小,統(tǒng)計(jì)字符串的字符個(gè)數(shù),遇到'\0'停止統(tǒng)計(jì),不統(tǒng)計(jì)'\0'。
3.知識(shí)點(diǎn)
3.1 對(duì)于數(shù)組
sizeof
:結(jié)果就是數(shù)組大小。
strlen
:在計(jì)算時(shí)會(huì)遍歷整個(gè)數(shù)組,往后遍歷的時(shí)候不一定能碰到'\0',會(huì)存在越界問題,
要么程序崩潰要么產(chǎn)生隨機(jī)值,但結(jié)果一定至少是數(shù)組長度。
3.1.1 數(shù)組中無'\0'
#include <stdio.h> int main() { char s[] = { 'a', 'b', 'c' }; printf("%d\n", sizeof(s)); printf("%d\n", strlen(s));//隨機(jī)值 return 0; }
3.1.2 數(shù)組有'\0'
(1)'\0'在最后
#include <stdio.h> int main() { char s[] = { 'a', 'b', 'c', '\0' }; printf("%d\n", sizeof(s)); printf("%d\n", strlen(s)); return 0; }
(2) '\0'在中間
#include <stdio.h> int main() { char s[] = { 'a', 'b','\0','c', }; printf("%d\n", sizeof(s)); printf("%d\n", strlen(s)); return 0; }
3.2 對(duì)于字符串
C語言中能夠保存字符串的,只有char類型的數(shù)組。
3.2.1 字符串無明顯的'\0'
#include <stdio.h> int main() { printf("%d\n", sizeof("abcd")); printf("%d\n", strlen("abcd")); return 0; }
、
3.2.2 字符串有明顯的'\0'
(1)'\0'在最后
#include <stdio.h> int main() { printf("%d\n", sizeof("abd\0")); printf("%d\n", strlen("abd\0")); return 0; }
(2)'\0'在中間
#include <stdio.h> int main() { printf("%d\n", sizeof("abc\0d")); printf("%d\n", strlen("ab\0d")); return 0; }
以上就是C語言入門篇--sizeof與strlen基礎(chǔ)理論的詳細(xì)內(nèi)容,更多關(guān)于C語言基礎(chǔ)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- C語言sizeof和strlen區(qū)別小結(jié)
- C語言中sizeof和strlen的區(qū)別詳解
- C語言中的strlen()和sizeof()對(duì)比分析
- C語言之sizeof與strlen的使用及區(qū)別
- 淺談C語言中的sizeof()和strlen()的區(qū)別
- 關(guān)于C語言strlen與sizeof區(qū)別詳情
- C語言中sizeof()與strlen()的區(qū)別詳解
- C語言中sizeof()與strlen()函數(shù)的使用入門及對(duì)比
- C語言中關(guān)于sizeof 和 strlen的區(qū)別分析
- C語言中sizeof 和 strlen的區(qū)別
相關(guān)文章
C/C++中的?Qt?StandardItemModel?數(shù)據(jù)模型應(yīng)用解析
QStandardItemModel?是標(biāo)準(zhǔn)的以項(xiàng)數(shù)據(jù)為單位的基于M/V模型的一種標(biāo)準(zhǔn)數(shù)據(jù)管理方式,本文給大家介紹C/C++中的?Qt?StandardItemModel?數(shù)據(jù)模型應(yīng)用解析,感興趣的朋友跟隨小編一起看看吧2021-12-12