Analysis of the difference between sizeof and strlen in C

  • 2020-04-02 02:57:33
  • OfStack

1. Calculate the operator sizeof at compile time, using the type or variable as the parameter to calculate the sizeof the memory occupied. Sizeof must be enclosed if the type, not if the variable name. Sizeof (x) can be used to define array dimensions such as:


printf("%dn", sizeof(short));

      The output is length 2 of the short integer. Sizeof returns the actual size when a structure type or variable is used as an argument, and sizeof returns the sizeof the entire array when used for a static array. The sizeof operator cannot return the sizeof a dynamically dispatched array or an external array

2, run time calculation strlen, can only use char* as an argument, and must end with "'\0". That's the length of the string. Such as:


char str[20]="0123456789";
int a=strlen(str); //The result is a=10
int b=sizeof(str); //The results of b = 20; < br / >

3. Handle static array:


char str[20]="0123456789";
int a=strlen(str); //A = 10; Strlen calculates the length of the string, ending the string with 0'. < br / > int b=sizeof(str); //B = 20. Sizeof calculates the sizeof the allocated array STR [20], regardless of what is stored in it. < br / >

4. Processing pointer:


char* ss = "0123456789";
sizeof(ss) //Result 4,

Ss is a character pointer to a string constant, sizeof gets the space occupied by a pointer. Sizeof (*ss) results in 1, *ss being the first character is essentially getting the memory space of the first '0' of the string, which is of type char, 1 byte. Strlen (ss)= 10, you must use strlen to get the length of the string

That's all there is to know about the difference between sizeof and strlen, and I hope you enjoy it


Related articles: