關於sizeof和strlen的區別和用法
一.需要明確strlen()是個字串函式,是統計一個字串從開始到"/0"(字串結束)之間字元的個數(不包含"/0")。字串可以是char *str1 = "asdaff"; 也可以是字元陣列形式 char str2[] = "asdadf"; 都可以統計字元數量。
二.sizeof是型別說明符,陣列名或表示式,不是個函式,是判斷資料型別長度的關鍵字。
為了方便理解和記憶,給出幾個典型例子。
char *str1 = "asdaf"; strlen(str1) =
5 sizeof(str1) = 8(僅僅是個指標)
char str2[10] = "asdfa"; strlen(str2) = 5 sizeof(str2) = 10
char str3[] = "asdfa"; strlen(str3) = 5 sizeof(str3) = 6(最後加個'\0')
int array1[] = {10, 15, 23}; sizeof(array1) = 12
int array2[5] = {10, 15, 23}; sizeof(str1)
第一次寫,寫的感覺好亂。。。。。
再次補充,寫了一個例子
3 int main(int ac, char **av)
4 {
5 char ac0[] = "abcdefghl";
6 char ac1[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g','h','l'};
7 char *ac2 = "abcdefghl";
8
9 printf("%d\n", strlen(ac0));
10 printf("%d\n", strlen(ac1));
11 printf("%d\n", strlen(ac2));
12 printf("%d\n", sizeof(ac0));
13 printf("%d\n", sizeof(ac1));
14 printf("%d\n", sizeof(ac2));
15
16 return 0;
17 }
結果為
9
9
9
10
9
8
可以自己細細揣摩一下