Differences between sizeof and strlen

Source: Internet
Author: User
Strlen only works as a counter. It starts scanning from a memory location (which can start with 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. Differences between strlen and sizeof: The strlen (char *) function is used to calculate the actual length of the string. The method is from the beginning to the First '\ 0'. If you only define that the initial value is not assigned to it, the result is not correct. It will be searched 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 while Sizeof () returns the memory size occupied by the variable declaration, not the actual length.In addition, sizeof is not a function, but an operator. strlen is a function. Sizeof (AA) returns 10int 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. Bytes The sizeof parameter of the array is not degraded. If it is passed to strlen, It is degraded 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 ); // B = 20; 6. The strlen result can be calculated only during running. It is used to calculate the string length, 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 transmitted by another parameter.

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, ending with the end character 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 value, 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 first '0' of the string, which is of the char type, strlen (SS) = 10 >>> to obtain the length of this string, use strlensizeof 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 When passing an array name to a function for 4, it will be completely degraded into a pointer ---------------------------------------------------------- do you know the differences 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; 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 that the memory size is 100 × 1strlen (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 × 4strlen (SS) error = "strlen" can only be char * and must end with '\ 0'. Char Q [] = "ABC "; Char P [] = "A \ n "; Sizeof (Q), sizeof (P), strlen (Q), strlen (P ); The result is 4 3 3 2.Example 2

Class X {int I; Int J; char K;}; 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 also gave a good explanation: Sizeof
You only need 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. A lot of things are clear. 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; sizeof a reference results in sizeof the size of a 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; // also 32 system ("pause ");}

R references the entire O object rather than the pointer to O, so the result of sizeof R is exactly the same as that of sizeof O.

Udfs implement strlen () Functions

The following example shows the source code for implementing the strlen function.

# Include <stdio. 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 ;}

Example 2

Int strlen (const char * Str) {assert (STR! = NULL); int Len = 0; while (* STR ++ )! = '\ 0') Len ++; return Len ;}

Example 3

Int strlen (const char * Str) {assert (STR); const char * P = STR; while (* P ++! = NULL); Return p-str-1 ;}

Example 4

Int strlen (const char * Str) {assert (STR); If (* STR = NULL) return 0; else return (1 + strlen (++ Str ));}

Example 5

/*** 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 ;}

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.

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.