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 uncertain.
Char aa [10] = {'\ 0'}; cout <strlen (aa) <endl; // The result is 0.
Char aa [10] = "jun"; cout <strlen (aa) <endl; // The result is 3.
Sizeof () returns the amount of 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 a parameter using a function, for example:
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 why sizeof (x) can be used to define the 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 used, sizeof returns the size of all arrays.
The sizeof operator cannot return the size of the dynamically assigned array or external array.
When the arguments array is passed as a parameter to the function, the pointer instead of an array is passed, and the first address of the array is passed,
For example:
Fun (char [8])
Fun (char [])
It 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:
After entering the function, copy it with memcpy. The length is passed in by another parameter.
Fun (unsiged char * p1, int len) {unsigned char * buf = new unsigned char [len + 1] memcpy (buf, p1, len );}
We can usually use sizeof and strlen to calculate the length of the string array.
After reading the detailed explanation above, we can see that there is a difference between the two. From this example, we can see clearly:
Char str [20] = "0123456789 ";
Int a = strlen (str); // a = 10; >>>> strlen calculates the length of the string, ending with 0x00 as the string.
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 will be 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, so it is 4
Sizeof (* ss) Result 1 = "* ss is the first character. In fact, it obtains the memory space occupied by the string's first '0', which is of the char type, 1 place
Strlen (ss) = 10 >>> to obtain the length of this string, use strlen
Sizeof returns the size of the byte occupied by the object. // correct
Strlen returns the number of characters. // correct
When sizeof is used, there is a special situation, that is, the array name to pointer transformation,
Char Array [3] = {'0 '};
Sizeof (Array) = 3;
Char * p = Array;
Strlen (p) = 1; // The result of sizeof (p) is 4.
When an array name is passed to a function, it is completely degraded into a pointer.
----------------------------------------------------------
After reading the above, do you know the difference between sizeof and strlen? If you still don't understand it, let's look at the following examples:
Example 1
Char * 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 compilation programs calculate sizeof as a type or variable length during compilation.
This is why sizeof (x) can be used to define the 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, calculated to the \ 0 position, so it is 10 + 1
Sizeof (* ss) Result 1 = "* ss is the first character
Char ss [100] = "0123456789 ";
The result of sizeof (ss) is 100 ===" ss indicates the size in the memory is 100 × 1
Strlen (ss) returns 10 ===" strlen is a function, and the internal implementation is calculated by a loop until \ 0.
Int ss [100] = "0123456789 ";
Sizeof (ss) Result 400 => ss indicates that the memory size is 100 × 4
Strlen (ss) Error ===" the strlen parameter 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 x X;
Cout <sizeof (X) <endl; Result 12 = memory completion
Cout <sizeof (x) <endl; Result 12 is the same as above.
Example 3
Char szPath [MAX_PATH]
If this is defined in the function, sizeof (szPath) will be MAX_PATH, but 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 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 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 a pointer of sizeof, 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 stack size of the pointer.
The processing of references in C ++ is special. The result of a sizeof reference is the size of a sizeof referenced object.
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
For the source code of several strlen functions, refer
Example 1
# 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, it is not allowed to implement library functions.
Call other library functions. 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.