Large Operating System Lab progress (9) ----- strlen () and sizeof

Source: Internet
Author: User
Tags first string

Strlenstrlen only works as a counter, which starts scanning from a certain location in the memory (it can be the start of a string, a location in the middle, or even an uncertain memory area, the counter value is returned until the first string Terminator '\ 0' is reached. Prototype: extern unsigned int strlen (char * s); in Visual C ++ 6.0, the prototype is size_t strlen (const char * string); where size_t is actually unsigned int, you can see the following code in VC6.0: typedef unsigned int size_t ;. Header file: string. h format: strlen (character array name) function: Calculate the length of string s (unsigned int type), excluding '\ 0'. Description: returns the length of s, excluding the terminator NULL. Example 1: (run in Visual C ++ 6.0) # include <string. h> # include <stdio. h> int main (void) {char * s = "Golden Global View"; printf ("% s has % d chars", s, strlen (s )); difference between getchar (); return 0;} and sizeof () strlen (char *) functions evaluate the actual length of the string, it is obtained from the beginning to the First '\ 0'. If you only define that the initial value is not assigned to it, the result is not fixed, it will continue from the first address of aa until '\ 0' is stopped. Char aa [10]; cout <strlen (aa) <endl; // The result is an indefinite char aa [10] = {'\ 0 '}; cout <strlen (aa) <endl; // The result is 0 char aa [10] = "jun"; cout <strlen (aa) <endl; // The result is 3, and sizeof () returns the memory occupied by the variable declaration, not the actual length. In addition, sizeof is not a function, but an operator, and strlen is a function. Sizeof (aa) returns 10 int a [10]; sizeof (a) returns 40 (according to the language int type c is two bytes c ++ is four java is two) the result type of the inclusizeof operator is size_t. In the header file, typedef is of the unsigned int type. This type ensures that it can accommodate the maximum object size. Inclusizeof is an operator (keyword) and strlen is a function. ⒊ Sizeof can be used as a parameter. strlen can only use char * as a parameter and must end with ''\ 0. Sizeof can also be used as parameters using functions, such as: short f (); printf ("% d \ n", sizeof (f ())); the output result is sizeof (short), that is, 2. The sizeof parameter of the struct array is not degraded. If it is passed to strlen, It is degraded to a pointer. Most compile programs calculate sizeof as a type or variable length during compilation. This is sizeof (x) can be used to define the reason for array dimension char str [20] = "0123456789"; int a = strlen (str); // a = 10; int B = sizeof (str ); // while B = 20; 6. the strlen result can be calculated only when running. It is used to calculate the length of the string, not the memory size occupied by the type. 7. If sizeof is a type, you must add an arc. If it is a variable name, you can do not add an arc. This is because sizeof is an operator and not a function. When a struct is applicable to a schema type or variable, sizeof returns the actual size. When a static space array is applied, sizeof returns the size of all arrays. The sizeof operator cannot return the size limit array of an array or an external array that is dynamically assigned. When passed as a parameter to the function, the pointer instead of an array is passed, and the first address of the array is transmitted, for example: fun (char [8]) fun (char []) is equivalent to fun (char *). In C ++, passing an array by parameters is always a pointer to the first element of the array, 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: Enter the function and copy it with memcpy, the length is passed into fun (unsiged char * p1, int len) {unsigned char * buf = new unsigned char [len + 1] memcpy (buf, p1, len );} when sizeof and strlen are often used, we usually calculate the length of the string array. After reading the detailed explanation above, we find that there is a difference between the two, from this example, we can see that char str [20] = "0123456789"; int a = strlen (str); // a = 10; >>>> strlen calculates the length of the string and ends with the string ending with 0x00. Int B = sizeof (str); // while B = 20; >>> sizeof calculates the memory space occupied by the allocated array str [20, the stored content is not changed. The above is the result of processing the static array. If it is a pointer, the result is different: char * ss = "0123456789"; sizeof (ss) result 4: ss is a character pointer to a String constant. sizeof obtains the space occupied by a pointer, which should be a long integer, therefore, it is 4 sizeof (* ss) Result 1 = "* ss is the first character. In fact, it is the memory space occupied by the string's first '0, it is of the char type and occupies 1 strlen (ss) = 10 >>> if you want to obtain the length of this string, then, use strlen sizeof to return the byte size of the object. // correct strlen returns the number of characters. // when sizeof is used correctly, a special case is that the Array name changes to the pointer, char Array [3] = {'0'}; sizeof (Array) = 3; char * p = Array; strlen (p) = 1; // Sizeof (p) result is 4 when an array name is passed to a function, it will be completely degraded into a pointer ---------------------------------------------------------- do you know the difference between sizeof and strlen after reading the above? If you still don't understand it, let's look at the following examples: the first example is char * ss = "0123456789"; sizeof (ss) result 4: "ss" refers to the character pointer sizeof (* ss) pointing to a String constant) result 1 = "* ss is the first character. Most compilers calculate sizeof as a type or variable length during compilation. This is sizeof (x) can be used to define the reason for array dimension char str [20] = "0123456789"; int a = strlen (str); // a = 10; int B = sizeof (str ); // B = 20; most compilation programs calculate sizeof as a type or variable length during compilation. This is sizeof (x) can be used to define the reason for array dimension char str [20] = "0123456789"; int a = strlen (str); // a = 10; int B = sizeof (str ); // B = 20; char ss [] = "0123456789"; sizeof (ss) Result 11 = "ss is an array and is calculated to the \ 0 position, therefore, 10 + 1 sizeof (* ss) Result 1 = "* ss is the first character char ss [100] =" 0123456789 "; sizeof (ss) the result is 100 = "ss" indicates the size of the memory is 100 × 1 strlen (ss). The result is 10 = "strlen is a function, internal implementation is to use a loop to calculate int ss [100] = "0123456789"; sizeof (ss) until \ 0) result 400: "ss" indicates that the memory size is 100 × 4 strlen (ss) error ===' strlen parameter can only be char * and must end with '\ 0' char q [] = "abc "; char p [] = "a \ n"; sizeof (q), sizeof (p), str Len (q), strlen (p); the result is 4 3 3 2. The second example class X {int I; int j; char k ;}; X x X; cout <sizeof (X) <endl; Result 12 = "cout <sizeof (x) <endl; result 12: If char szPath [MAX_PATH] In the third example is defined in the function, sizeof (szPath) will be MAX_PATH, however, when szPath is declared as a virtual parameter (void fun (char szPath [MAX_PATH]), sizeof (szPath) is 4 (pointer size) another netizen explained that sizeof only needs to grasp one key point: Stack program storage is distributed in three areas: Stack, static, and dynamic. Objects that can be operated directly from code, including any type of variables and pointers, are all on the stack; dynamic and static storage areas are operated indirectly by the pointer on the stack. The sizeof operator calculates the projection volume of an object on the stack. Remember this. Char const * static_string = "Hello"; sizeof (static_string) is a pointer of sizeof, so in 32bit system, it is 4 char 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 (string) is sizeof a pointer, so it is still 4. Unlike the first one, this pointer points to a dynamic storage area instead of a static storage area. No matter where the Pointer Points to, sizeof gets the reference processing in the stack size C ++ of the pointer; the result of a sizeof reference is the size of a sizeof referenced object. Therefore, struct O {int a, B, c, d, e, f, g, h ;}; int main () {O & r = * new O; cout <sizeof (O) <endl; // 32 cout <sizeof r <endl; // It is also 32 system ("PAUSE");} r references the entire O object rather than the pointer to O, so the sizeof r result is exactly the same as sizeof O. Use a custom function to implement strlen (). For the source code of several strlen functions, see ----------------------------------------------------- 1: start -------------------------------------- # include <. h> # include <assert. h> typedef unsigned int u_int; u_int Mystrlen (const char * str) {u_int I; assert (str! = NULL); for (I = 0; str [I]! = '\ 0'; I ++); return I;} else 1: end limit 2: start ---------------------------------------- int strlen (const char * str) {assert (str! = NULL); int len = 0; while (* str ++ )! = '\ 0') len ++; return len;} else 2: end when starting 3: start ---------------------------------------------- int strlen (const char * str) {assert (str ); const char * p = str; while (* p ++! = NULL); return p-str-1;} limit 3: end limit 4: start ---------------------------------------- int strlen (const char * str) {assert (str ); if (* str = NULL) return 0; else return (1 + strlen (++ str);} ----------------------------------------------- 4: end ---------------------- ------------------ Limit 5: start --------------------------------------/*** strlen-Find the length of a string * @ s: The string to be sized */size_t strlen (const char * s) {const char * SC; for (SC = s; * SC! = '\ 0'; ++ SC)/* nothing */; return SC-s;} else 5: end ------------------------------------------ the above implementation methods are similar, some use variables, and some use pointers. The last one is recursive. In fact, when implementing library functions, it is stipulated that other library functions cannot be called. Here we just give you a method to implement strlen without variables.

Related Article

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.