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

The difference between sizeof and strlen in C language

2022-07-06 02:41:00 Mr. Xiao Yang's treasure house

The main differences are as follows :
1、sizeof It's the operator ,strlen yes C Language standard library functions .
2、 strlen It measures the actual length of the string , With ’\0’ end , The returned result does not include ’\0’ .
3、 and sizeof It measures the allocated size of characters , Its parameters can be arrays 、 The pointer 、 type 、 object 、 Functions, etc .
To be specific , When the parameters are as follows ,sizeof The meaning of the returned value is as follows :

Array - The amount of array space allocated at compile time ;

The pointer - The amount of space used to store the pointer ;

type - The size of the space occupied by this type ;

object - The actual space occupied by the object ;

function - The space occupied by the function return type ;

Example 1:
char *str1=“absde”;
char str2[]=“absde”;
char str3[8]={‘a’,};
int str4[8]={‘a’,};
char ss[] = “0123456789”;

Output :

sizeof(str1); // 4, It calculates the size of pointer memory , Include ’\0’
sizeof(str2); // 6 , It calculates the memory size of the string , Include ’\0’
sizeof(str3); // 8 , The calculation is char Memory size of type array
sizeof(str4); // 32 , The calculation is int Memory size of type array
sizeof(ss); // 11 , It calculates the size of the string , Include ’\0’
strlen(str1); // 5 , The length of the string is calculated , barring ‘\0’
strlen(str2); // 5 , The length of the string is calculated , barring ‘\0’
strlen(str3); // ? , Because the string needs to be found ’\0’ To end , To be in ’a’ And then I found ’\0’, So it's a random value
strlen(str4); // ? , Because the string needs to be found ’\0’ To end , To be in ’a’ And then I found ’\0’, So it's a random value
strlen(ss); // 10 , The length of the string is calculated , barring ‘\0’

Example 2:
what is the output of this code?
char s[20]=“Hello\0Hi”;
printf(“%d %d”,strlen(s),sizeof(s));

A 5 9
B 7 20
C 5 20
D 8 20

right key C

Example 3
char str[]=“hello”;
char *p=str;
int n=10;
// Please calculate
sizeof(str); //6,5+1=6,1 representative ’\0’
sizeof§; //4, For the pointer
sizeof(n); //4, The storage space occupied by shaping

void func(char str[100])
{
sizeof(str); //4, here str It has been converted to a pointer
}

void *p=malloc(100);

sizeof§;//4, Pointer size
————————————————
Copyright notice : This paper is about CSDN Blogger 「 Bitter gourd 」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/qq_52368521/article/details/124950895

原网站

版权声明
本文为[Mr. Xiao Yang's treasure house]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060235348701.html