当前位置:网站首页>The difference between sizeof and strlen

The difference between sizeof and strlen

2022-06-25 15:02:00 52Hertz. six hundred and fifty

1、 meaning

sizeof It's the operator
strlen Is the function
sizeof() It works on everything , And the whole size of the calculation
strlen() The scope of action is relatively narrow , Only string sizes can be calculated ( barring \0), And the string is \0(NULL) For the end sign , So as long as strlen meet \0 ends

2、sizeof

sizeof The code for

#include <stdio.h>
#include <string.h>
int main()
{
    
    char str[30] = "hello good\0man";// Written 14 Characters 
	char b[] = "sad";
    int c[5] = {
    2,5,4,6,8};
    printf(" Array str Its size is %d byte \n",sizeof(str));
    printf(" Array a Its size is %d byte \n",sizeof(b));
    printf(" Array b Its size is %d byte \n",sizeof(c));
    return 0;
}

Running results

Array str Its size is 30 byte
Array a Its size is 4 byte
Array b Its size is 20 byte

why?
str[30], When you create an array, you already give str Opens the 30 Byte size space , So the result is 30

Array b Although the stored string is sad, But it's actually d There's another one in the back \0, Practice means a[] In fact, it is equal to asd\0, So there are four bytes , because \0 Is also a byte

Array c Deposited 5 It's an integer , The size of an integer is 4 Bytes , therefore c Size is 20 byte , instead of 5 Bytes , because sizeof Is to measure the whole

3、strlen

strlen() The code for

#include <stdio.h>
#include <string.h>
int main()
{
    
    char str[30] = "hello good\0man";// Written 14 Characters 
	char b[] = "sad";
    printf(" Array str Its size is %d byte \n",strlen(str));
    printf(" Array a Its size is %d byte ",strlen(b));
    return 0;
}

Running results

Array str Its size is 10 byte
Array a Its size is 3 byte

why?
Array str There is one in the middle of the string stored in \0, So I met \0, End the measurement , Because the end of the string is \0, So we only measured 10 Characters , Finish ahead of time

Array a There are actually four characters ,asd\0, But we said , String to \0 end , therefore strlen Measured to d Hidden behind \0, It's over

原网站

版权声明
本文为[52Hertz. six hundred and fifty]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200513342556.html