I have recently asked a question about sizeof in the forum, and I have never been able to solve this problem well. I just want to give a more detailed summary of it today, at the same time, I would like to compare it with strlen. If it can help you a little bit, this is my greatest pleasure.
1. First, let's take a look at the definitions of sizeof and strlen on msdn:
First, let's take a look at how sizeof is defined on msdn:
Sizeof operatorsizeof expressionthe sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types ). this keyword returns a value of Type size_t.the expression is either an identifier or a type-cast expression (a type specifier enclosed inparentheses ). when applied to a structure type or variable, sizeof returns the actual size, which may have depadding bytes inserted for alignment. when applied to a statically dimensioned array, sizeofreturns the size of the entire array. the sizeof operator cannot return the size of dynamicallyallocated arrays or external arrays.
Then let's take a look at how strlen is defined:
Strlenget the length of a string. routine required header: strlen <string. h> size_t strlen (const char * string); parameterstring: null-terminated stringlibrariesall versions of the C run-time libraries. return valueeach of these functions returns the number of characters in string, excluding the terminalnull. no return value is reserved to indicate an error. remarkseach of these functions returns the number of characters in string, not including theterminating null character. wcslen is a wide-character version of strlen; the argument ofwcslen is a wide-character string. wcslen and strlen behave identically otherwise.
2. Let's use several examples.
Example 1:
Char * Ss = "0123456789"; sizeof (SS) Result 4 ===" SS is the character pointer to a String constant sizeof (* ss) result 1 = "* ss is the first character char ss [] =" 0123456789 "; sizeof (SS) Result 11 =" SS is an array, the value is calculated to the \ 0 position. Therefore, 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 of 100 × 1strlen (SS) in the memory) the result is 10 =, strlen is a function. The 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: The 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; cout <sizeof (x) <Endl; result 12: The cout <sizeof (x) <Endl is completed in the memory. 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)
Iii. deep understanding of sizeof.
- 1. The result type of the sizeof 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.
-
- 2. sizeof is an operator and strlen is a function.
-
- 3. sizeof can be a type parameter. strlen can only be a char * 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.
-
- 4. the sizeof parameter of the array is not degraded. If it is passed to strlen, It is degraded to a pointer.
-
- 5. Most CompilationProgramDuring compilation, sizeof is computed as the type or variable length. 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.
-
- 8. When a structure type or variable is applied, 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 of the dynamically assigned array or external array.
- 9. When an array is passed as a parameter to a 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 *). Passing an array in C ++ 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 );}
For more information, see C ++ primer?
-
- 10. to calculate the size of the structure variable, we must discuss the Data Alignment issue. To achieve the fastest CPU access speed (this is related to the number of CPU operations. For details, refer to some books on computer Principles ), when processing data, C ++ often calculates the size of the members in the Structure Variable in multiples of 4 or 8, which is called data alignment ). This may waste some memory, but the speed is faster theoretically. Of course, this setting will cause inconvenience when reading and writing data files generated by other applications or exchanging data. Alignment settings in ms vc ++, sometimes sizeof gets different from the actual. Generally, add the # pragma pack (n) Setting in VC ++. or if you want to store data by byte without Data Alignment, you can modify the data alignment on the advanced compiler page in the Options dialog box to be byte aligned.
-
- 11. The sizeof operator cannot be used for function types. It is not completely type or bit field. An incomplete data type refers to a data type with an unknown storage size, such as an array type with an unknown storage size, an unknown content structure, a union type, and a void type. For example, if sizeof (max) is defined as int max () and sizeof (char_v), if char_v is defined as char char_v [Max] and Max is unknown, sizeof (void) none of them are in the correct format
Iv. Conclusion
Sizeof usage.
- 1. One major purpose of the sizeof operator is to communicate with routines such as storage allocation and I/O systems. For example:
Void * malloc (size_t size), size_t fread (void * PTR, size_t size, size_t nmemb, file * stream ).
- 2. Use it to view the unit bytes occupied by a type of object in memory.
Void * memset (void * s, int C, sizeof (s ))
- 3. When an object is dynamically allocated, the system can know how much memory to allocate.
- 4. It is easy to expand some types. In Windows, many internal types have a dedicated field that is used to store the size of these types of bytes.
- 5. because the number of bytes of the operand may change during implementation, we recommend that you use sizeof to replace constant calculation when it comes to the size of the operand bytes.
- 6. If the operand is an array parameter in the function or a function-type parameter, sizeof gives the pointer size.
(By Fang bingyi)