天天看點

C語言 sizeof和strlen的相同點與不同點 ----by xhxh

相同點: 都可以計算字元串數組中元素的個數

不同點:

1.sizeof()操作符以位元組形式給出了其操作數的存儲大小,要計算字元串數組中元素的個數需要進行簡單的四則運算,即sizeof(str)/sizeof(str[0]),strlen()則直接帶入參數就行,即strlen(str)

2.sizeof()不會過濾"\0",strlen()直接對"\0"進行了過濾

示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    printf("the first way :\n");
    char str[3] = {'a','b','c'};
    printf("the num of str :%ld\n",sizeof(str)/sizeof(str[0]));

    printf("the second way :\n");
    char str2[128] = "hello";
    printf("the num of str2 (hello):%ld\n",sizeof(str2)/sizeof(str2[0]));

    printf("the third way :\n");
    char str3[128] = "hello";
    printf("the num of str3 :%ld\n",strlen(str3));
    
    return 0;
}
           
C語言 sizeof和strlen的相同點與不同點 ----by xhxh

在second way當中,我們為str2開辟了128位元組的空間,但是我們隻為前五指派,在計算當中sizeof沒有将str2後面的"\0"過濾掉(我們隻為str2前五項指派為hello,程式會自動将後面的123個空位初始化為"\0")

繼續閱讀