Deep sizeof the use of detailed _c language

Source: Internet
Author: User
Often in C programming, do not understand sizeof is a bit unreasonable, this article can not sizeof and strlen difference Oh, although this contrast is very classic, but, will point it.

first, the concept of sizeof
sizeof is a single order operator in C language, such as other operators in C + + 、--. It's not a function. The sizeof operator gives the storage size of its operands in bytes.
Operands can be an expression or a type name enclosed in parentheses. The storage size of the operand is determined by the type of operand.

second, the use method of sizeof
1. For data types
sizeof use form: sizeof (type)
Data types must be enclosed in parentheses. such as sizeof (int), there are sizeof int, or sizeof (variable) three ways.

2. For variable
sizeof use form: sizeof (var_name) or sizeof Var_name
Variable names can be enclosed without parentheses. such as sizeof (Var_name), sizeof var_name and so on are the correct form. Parenthesized usage is more common, most programmers take this form.
   Note:The sizeof operator cannot be used with a function type, an incomplete type, or a bit field. An incomplete type refers to a data type with an unknown storage size, such as an array type of unknown storage size, structure or union type of unknown content, void type, and so on.
such as sizeof (max) If the variable max is defined as int max (), sizeof (CHAR_V) if CHAR_V is defined as Char Char_v [MAX] and Max is unknown, sizeof (void) is not the correct form.  

Iii. results of the sizeof

The result type of the sizeof operator is size_t, which is typedef in the header file as the unsigned int type. This type guarantees the byte size of the maximum object that the implementation is built to hold.
1, if the operand has type char, unsigned char or signed char, the result is equal to 1.
ANSI C formally stipulates that the character type is 1 bytes.
   2, int, unsigned int, short int, unsigned short, long int, unsigned long, float, double, long double type sizeof
There is no specification in ANSI C that size depends on implementation, which can generally be 2, 2, 2, 2, 4, 4, 4, 8, 10, respectively.
3, when the operating number is Pointers, sizeof relies on the compiler. For example, in Microsoft c/c++7.0, the near class pointer byte number is 2,FAR, and the huge class pointer byte number is 4. General Unix has a pointer byte of 4.
4, when the operand has Array Type, the result is the total number of bytes in the array.
5, Union TypeThe sizeof of the operand is the number of bytes of its maximum byte member. The sizeof of the struct type operand is the total number of bytes of this type of object, including any pad complement.
Let's look at the following structure:
struct a{
Char b;
Double X;
A
On some machines sizeof (a) = 12, while the general sizeof (char) + sizeof (double) = 9.
This is because the compiler inserts an empty space in the structure to control the address alignment of each member object when it considers alignment issues. A struct member x, such as the double type, is placed at an address that is divisible by 4.
6, if the operand is a function of the array parameter or function type parameter, sizeof gives its pointer size.

Iv. the relationship between sizeof and other operators
sizeof Precedence (the precedence of each operator can be referenced C-language operator precedence list (verbose):) is level 2, the ratio/,%, and so on level 3 operator priority high. It can be used with other operators to form an expression. such as i*sizeof (int), where i is an int type variable.

v. Main uses of sizeof
1. One of the main uses of the sizeof operator is to communicate with routines like storage allocations 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. Another main use of sizeof is to compute the number of elements in an array. For example:
void * memset (void *s,int c,sizeof (s)).

VI. Recommendations
Because the number of bytes in the operand may vary in implementation, it is recommended that sizeof be used instead of constant calculations when it comes to operand byte sizes.
This article mainly includes two parts, the first part focuses on the VC, how to use sizeof to find the size of the structure, as well as easy to appear problems, and to solve the problem of the method,
The second part sums up the main usage of sizeof in VC.
1, sizeof application in the structure of the situation
See the following structure:
struct MYSTRUCT
{
Double dda1;
Char DDA;
int type
};
What will happen to the structure mystruct adoption sizeof? How much is sizeof (MYSTRUCT)? Perhaps you would ask:
sizeof (MyStruct) =sizeof (double) +sizeof (char) +sizeof (int) =13
But when you test the size of the above structure in VC, you will find that sizeof (MYSTRUCT) is 16. Do you know why the VC will come up with such a result?
In fact, this is a VC for variable storage of a special treatment. In order to improve the CPU storage speed, VC for some variables to start the address of the "alignment" processing. By default, VC stipulates that the offset of the starting address of each member variable in relation to the starting address of the structure must be a multiple of the number of bytes occupied by the type of the variable. The common types of alignment (vc6.0,32 bit systems) are listed below.
Each member variable at the time of storage according to the order in the structure of the application space, in accordance with the above alignment adjustment position, the blank byte VC will automatically fill. At the same time VC to ensure that the size of the structure of the structure of the number of bytes (that is, the structure of the maximum space occupied by the type of the number of bytes) multiples, so after the last member variable request space, will also automatically fill the blank bytes as needed.
The following examples to illustrate how the VC to store the structure.
struct MYSTRUCT
{
Double dda1;
Char DDA;
int type
};
sizeof (MyStruct) =8+1+3+4=16,
One of the 3 bytes is automatically filled with VC, without any meaningful things.
Attach: Change the default byte alignment of the C compiler
By default, the C compiler allocates space for each variable or data unit according to its natural boundary condition. Generally, you can change the default boundary condition by using the following methods:
· Using pseudo-directive #pragma pack (n), the C compiler is aligned according to n bytes.
· Use the pseudo Directive #pragma pack () to cancel the custom byte alignment and restore the default alignment.
In addition, there are also the following ways:
· __attribute ((aligned (n)) to align the member of the structure to the N-byte natural boundary. If the length of a member in the structure is greater than N, it is aligned according to the length of the maximum member.
· __ATTRIBUTE__ ((packed)), cancels the optimized alignment of the structure during compilation, and aligns to the actual number of bytes occupied.

Summary of sizeof usage
In VC, sizeof has a lot of usage, and it is easy to cause some mistakes. The following is a summary of the usage of sizeof based on the parameters behind sizeof.
A parameter is either a data type or a generic variable. such as sizeof (int), sizeof (long), and so on. It should be noted that the results of different system systems or different compilers may be different. For example, the int type occupies 2 bytes in a 16-bit system and occupies 4 bytes in a 32-bit system.
B The argument is an array or pointer. The following examples illustrate.
int A[50]; sizeof (a) =4*50=200; To find the size of the space the array occupies
int *a=new int[50]; sizeof (a) = 4; A is a pointer, sizeof (a) is the size of the pointer, in a 32-bit system, of course, it occupies 4 bytes.
C parameter is a struct or class. sizeof applications are identical in the handling of classes and structures. But there are two points to note:
The first, struct, or static member of a class does not affect the size of the struct or class, because the storage location of the static variable is independent of the structure or the instance address of the class.
Second, the size of a struct or class without a member variable is 1, since each instance of the struct or class must be guaranteed to have a unique address in memory.
The following examples illustrate:
Class test{int a;static double C}; sizeof (Test) =4.
Test *s; sizeof (s) =4,s is a pointer.
Class test1{}; sizeof (test1) = 1;
D parameter is other. The following examples illustrate.
int func (char s[5]);
{
cout << S; The parameters of a function are processed as a pointer when passed, so sizeof (s) is actually the size of the pointer.
return 1;
}
sizeof (func ("1234")) = 4; Because the return type of func is int, it is equivalent to sizeof (int).

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.