"Reprint" The difference between strlen and sizeof

Source: Internet
Author: User

Self Summary:when sizeof is used, if the array variable is the size of the array variableChar a[10]; sizeof (a) =10If the pointer is a pointer size and the array variable is passed as a function parameter, it will degenerate into a pointer, and the function is not aware of the original array sizeChar *s= "ABCDDDDDD"; sizeof (s) = 4 pointer void f (char a[]) {sizeof (a) = 4 pointer} under reprint from Baidu Encyclopedia----------------------------------------------------------- -------------------- header File: string.h format:strlen (character array name) function: Calculates the length of the string s (unsigned int), excluding ' Description: Returns the length of S, not including The Terminator null. related functions: TCHAR. H routine _unicode & _mbcs not DEFINED_MBCS Defined_unicode defined _tcslen
Strlen Strlen Wcslen  
_tcsclen Strlen _mbslen Wcslen
2 Program example editing Example 1: (Run through in visual c++6.0)
123456789 #include<string.h>#include<stdio.h>intmain(void){    char*s="GoldenGlobalView";    printf("%s has %d chars",s,strlen(s));    getchar();    return0;}
3 different sizeof editions strlen (char*) function is the actual length of the string, it is calculated from the beginning to meet the first ' "", if you only define the initial value is not assigned to it, the result is uncertain, it will be from the AA header address has been looking down until the encounter ' " Char Aa[10];cout<<strlen (AA) <<endl; The result is a variable char aa[10]={' + '}; Cout<<strlen (AA) <<endl; The result is 0char aa[10]= "June"; Cout<<strlen (AA) <<endl; The result is 3 (the error here, the result is also uncertain, if the compiler put other non-0 strings in aa[10] memory address, strlen result is still uncertain, MSP430 in IAR compiled test) char aa[5]= "Hello";cout<< strlen (AA) <<endl; Result 5 (here is the error, for the reason, because in real memory, Hello is not necessarily empty) and sizeof () returns the amount of memory after the variable declaration, not the actual length, in addition to sizeof is not a function, just a take byte operator, strlen is a function. sizeof (AA) returns 10int a[10]; sizeof (a) returns 40 (according to the language int c is four bytes C + + is four Java is two) the result type of the ⒈sizeof operator is size_t, which is a typedef of the unsigned int type in the header file. This type guarantees that the byte size of the largest object being built can be accommodated. ⒉sizeof is the byte operator (keyword), and strlen is a function. ⒊sizeof can use the type parameter, strlen can only use char* to do the parameters, and must be "" "to end. sizeof can also use functions for parameters such as short f ();p rintf ("%d\n", sizeof (f ())), and the result of the output is sizeof (short), or 2. ⒋ array does sizeof parameter does not degenerate, passes to the strlen to degenerate as the pointer. ⒌ most compilers calculate the length of a type or variable at compile time. This is the reason that sizeof (x) can be used to define the number of dimensions of the array char str[20]= "0123456789"; long A=strlen (str);//a=10;int b=sizeof (str);//And B=20;6.strlenThe results are calculated at run time and are used to calculate the length of the string, not the size of the memory. 7.sizeof after if the type must be parentheses, if the variable name can be non-parenthesized. This is because sizeof is an operator and not a function. ⒏ when applied to a struct type or variable, sizeof returns the actual size, when applied to a static spatial array, sizeof reverts the dimensions of all arrays. The sizeof operator cannot return a dynamically assigned array or the size of an outer array ⒐ array as a parameter to the function simultaneous is a pointer instead of an array, passing the first address of the array, such as: Fun (char [8]) Fun (char []) is equivalent to Fun (char *) in C + + The parameter passing array is always a pointer to the first element of the array, and the compiler does not know the size of the array if you want to know the size of the array in the function, you need to do this: After entering the function, copy it with memcpy, and the length is passed into the fun by another parameter (unsiged char *p1,int len) {unsigned char* buf = new unsigned char[len+1] memcpy (Buf,p1,len);} We can often use sizeof and strlen, usually to calculate the length of the string array to see the above detailed explanation, found that the use of the two are still different, from this example can be seen very clearly: char str[20]= "0123456789"; int A=strlen (str); a=10; >>>> Strlen calculates the length of the string to end with the Terminator 0x00 for the string. int b=sizeof (str); and b=20; >>>> sizeof calculates the size of the memory space allocated by the array str[20], which is not changed by the contents stored inside it. Above is the result of the static array processing, if the pointer, the result is not the same char* SS = "0123456789"; sizeof (ss) result 4>>>>ss is a pointer to a character string constant, sizeof Obtained is a pointer to the value of the space, should be a long integer, so is the 4sizeof (*SS) result 1>>>> *ss is the first character is actually obtained the first bit of the string "0" of the memory space, is a char type, accounted for 1 Bit strlen (ss) = >>>> If you want to get the length of this string, be sure to use sTrlensizeof returns the size of the bytes occupied by the object. The correct strlen returns the number of characters. When using sizeof correctly, there is a very special case, that is, the array name to Pointer Metamorphosis, char array[3] = {' 0 '};sizeof (Array) = = 3;char *p = Array;strlen (p) = = 1;//sizeof ( p) The result is 4 when passing an array name into a function, It will completely degenerate into a pointer----------------------------------------------------------read above do you know the difference between sizeof and strlen? If you don't understand, let's look at some examples:A first examplechar* ss = "0123456789"; sizeof (ss) Result 4 = = = SS is a character pointer to a string constant sizeof (*SS) result 1 = = = *ss is the first character most of the compilers have computed sizeof at compile time as a type or The length of the variable this is the reason that sizeof (x) can be used to define the number of dimensions of the array char str[20]= "0123456789"; int A=strlen (str);//a=10;int b=sizeof (str);//And B=20;char SS [] = "0123456789"; sizeof (ss) Result 11 = = = "SS is an array, calculated to the location of the ss[100, so is 10+1sizeof (*SS) Result 1 = = =" *ss is the first character char 0123456789] = "siz"; EOF (ss) result is 100 = = = SS indicates size in memory 100x1strlen (ss) result is 10 = = = "Strlen is a function, the internal implementation is calculated by a loop before the ss[100] =" 0123456789 "; sizeof (ss) Result 400 = = = SS indicates size in memory 100x4strlen (ss) Error = = = Strlen parameter can only be char* and must be char q[]= "abc" with "p[]="; sizeof (q), sizeof (p), strlen (q), strlen (p); The result is 4 3 3 2A second exampleclass x{int i; Int J; char K;}; x x;cout<<sizeof (x) <<endl; Result 12 = = = Memory padded cout<<sizeof (x) <<endl; Results 12 Ibid.A third exampleChar Szpath[max_path] If defined within a function, then sizeof (szpath) will be MAX_PATH, but when the szpath is declared as a virtual parameter (void Fun (char Szpath[max_path]), sizeof (Szpath) is 4 (pointer size) There is also a Netizen's explanation is also very good: actually understand sizeof only need to grasp one point: Stack program storage distribution has three areas: stack, static and dynamic. Objects that can be manipulated directly from code, including any type of variable, pointer, are on the stack, and dynamic and static stores are indirectly manipulated by pointers on the stack. The sizeof operator calculates the projected volume of the object on the stack; Remembering this is a lot of things that are clear. Char Const * static_string = "Hello"; sizeof (static_string) is a pointer to sizeof, so the 32bit system is 4char stack_string[] = "Hello" sizeof (stack_string) is an array of sizeof, so it is 6 * sizeof (char) char * string = new char[6];strncpy (String, "Hello", 6 "); sizeof (str ing) is a pointer to sizeof, so it's still 4. And the first difference is that this pointer points to a dynamic store instead of a static storage area. Regardless of where the pointer is pointing, sizeof gets the stack size of the pointer. The handling of references in C + + is special; sizeof a reference results in the size of a referenced object in sizeof; so struct o{int a,b,c,d,e,f,g,h;}; int main () {O & r = *new o; cout << sizeof (o) << Endl;//cout << sizeof R << Endl;//also 3 2 System ("PAUSE");} R refers to the entire O object instead of the pointer to O, so sizeof R results in exactly the same as sizeof O. Custom functions implement the functions of the strlen () function below are some examples of implementing the strlen function of the source code for everyone reference 1
123456789 #include<stdio.h>#include<assert.h>typedefunsignedintu_int;u_intMystrlen(constchar*str){u_inti;assert(str!=NULL);for(i=0;str[i]!=‘\0‘;i++);returni;}
Example 2
1234567 intstrlen(constchar*str){assert(str!=NULL);intlen=0;while((*str++)!=‘\0‘)len++;returnlen;}
Example 3
123456 intstrlen(constchar*str){assert(str);constchar*p=str;while(*p++!=NULL);returnp-str-1;}
Example 4
1234567 intstrlen(constchar*str){assert(str);if(*str==NULL)return0;elsereturn(1+strlen(++str));}
Example 5
123456 /***strlen-Findthelengthofastring*@s:Thestringtobesized*/size_tstrlen(constchar*s){constchar*sc;for(sc=s;*sc!=‘\0‘;++sc)/*nothing*/;returnsc-s;}
All of the above implementations are very similar, some use variables, and some use pointers. The last one used is a recursive approach. In fact, in the implementation of the library function, it is not possible to call other library functions, here is just a method, you can use the variable can be implemented strlen

"Reprint" The difference between strlen and sizeof

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.