Sizeof and strlen

Source: Internet
Author: User

Http://www.vckbase.com/document/viewdoc? Id = 1054

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 in parentheses).When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated 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 string LibrariesAll versions of the C run-time libraries.Return ValueEach of these functions returns the number of characters in string, excluding the terminal NULL. No return value is reserved to indicate an error.RemarksEach of these functions returns the number of characters in string, not including the terminating null character. wcslen is a wide-character version of strlen; the argument of wcslen 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 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;
  • 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.

 

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.