【初識C語言】sizeof、strlen基礎知識點及用法
阿新 • • 發佈:2021-01-27
文章目錄
1.sizeof
(1)若求字串佔據 空間 的大小,包括字串結尾處預設的’\0’。
(2)若所求不是字串的大小,求的是陣列、型別等的大小,不用考慮’\0’,因為不是字串,在結尾處無預設的’\0’。
(3)若明顯出現’\0’,則統計。
2.strlen
求字串內容的大小,遇到’\0’停止統計,不統計’\0’。
3.知識點
3.1 對於陣列
sizeof:結果就是陣列大小。
strlen:在計算時會遍歷整個陣列,往後遍歷的時候不一定能碰到’\0’,會存在越界問題,要麼程式崩潰要麼產生隨機值,但結果一定至少是陣列長度。
3.1.1 陣列中無’\0’
#include <stdio.h>
int main()
{
char s[] = { 'a', 'b', 'c' };
printf("%d\n", sizeof(s));
printf("%d\n", strlen(s));//隨機值
return 0;
}
3.1.2 陣列有’\0’
(1)’\0’在最後
#include <stdio.h>
int main()
{
char s[] = { 'a', 'b', 'c', '\0' };
printf("%d\n", sizeof(s));
printf("%d\n", strlen(s));
system("pause");
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 對於字串
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>
#include <windows.h>
int main()
{
printf("%d\n", sizeof("abd\0"));
printf("%d\n", strlen("abd\0"));
system("pause");
return 0;
}
(2)’\0’在中間
#include <stdio.h>
int main()
{
printf("%d\n", sizeof("abc\0d"));
printf("%d\n", strlen("ab\0d"));
system("pause");
return 0;
}