天天看点

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")

继续阅读