In VC, sizeof has many usage and may cause some errors. Next, we will summarize the usage of sizeof based on the parameters following sizeof.
A. the parameter is of the data type or is A common variable:
For example, sizeof (int) and sizeof (long.
In this case, it should be noted that the results of different system systems or compilers may be different.
For example, the int type occupies 2 bytes in a 16-bit system and 4 bytes in a 32-bit system.
B. the parameter is an array or pointer:
Int a [50]; // sizeof (a) = 4*50 = 200; calculates the space occupied by the array.
Int * a = new int [50]; // sizeof (a) = 4; a is a pointer, and sizeof (a) is the pointer size. In a 32-bit system, of course, it occupies 4 bytes.
C. The parameter is a structure or class:
Sizeof applications process classes and structures in the same way. You need to consider byte alignment (in another article: C ++ custom struct and class memory alignment ). Note the following points:
First, static members in the structure or class do not affect the structure or class size, because the storage location of static variables is irrelevant to the instance address of the structure or class.
Second, the size of the structure or class (non-virtual) without member variables is 1, because each instance of the structure or class must have a unique address in the memory.
Third, the class that contains the virtual function or the class that inherits the virtual function must be counted as the four bytes occupied by the virtual table pointer.
The following is an example:
Class Test {int a; static double c}; // sizeof (Test) = 4.
Test * s; // sizeof (s) = 4, and s is a pointer.
Class test1 {}; // sizeof (test1) = 1;
Class test2 {virtual void print () {}}; // sizeof (test2) = 4;