Sizeof function: calculate the number of bytes in the Data Space
1. Comparison with strlen ()
Strlen calculates the number of characters in the character array. It ends with "\ 0" and does not count as an array element of '\ 0.
Sizeof memory space occupied by computing data (including arrays, variables, types, struct, etc.), expressed by the number of nodes (of course, used in the character array to calculate the size of "\ 0 ).
2. sizeof operations for pointers and static Arrays
Pointers can be viewed as one type of variables. The sizeof operation result for all pointer variables is 4.
Example 1: char * P;
Sizeof (p) = 4;
Sizeof (* P) = 1; // equivalent to sizeof (char );
Instance 2:
For static arrays, sizeof can directly calculate the array size;
Example: int A [10];
Char B [] = "hello ";
Sizeof (a) equals 4*10 = 40;
Sizeof (B) is 6;
Void fun (char P [])
{
Sizeof (p); // equals to 4. When an array is used as a parameter, the array name is used as a pointer !!
}
Example 3 (classic question ):
Double * (* A) [3] [6];
Cout <sizeof (a) <Endl; // 4 A is a pointer
Cout <sizeof (* A) <Endl; // 72 * A is an array with 3*6 pointer Elements
Cout <sizeof (** A) <Endl; // 24 ** A is the Six pointers of the array in one dimension.
Cout <sizeof (*** A) <Endl; // 4 *** A is the first pointer of one dimension.
Cout <sizeof (***** A) <Endl; // 8 ***** A is a double variable.
Problem Analysis:
First, let's take a look
: Int (* P) [4]; // defines a pointer pointing to an object composed of four integer Elements
Int A [3] [4]; // defines a two-dimensional array. Both A and P are of the same pointer type.
A is a very strange definition, which indicates a pointer to an array of the double * [3] [6] type. Since it is a pointer, sizeof (a) is 4.
Since a is a pointer of the double * [3] [6] type, * a indicates a multi-dimensional array of the double * [3] [6] type. Therefore, sizeof (*) = 3*6 * sizeof (double *) = 72.
Similarly, ** A indicates an array of the double * [6] type. sizeof (** A) = 6 * sizeof (double *) = 24.
* ** A indicates an element, that is, double *. Therefore, sizeof (*** A) = 4.
* *** A is a double, so sizeof (*** A) = sizeof (double) = 8.
Sizeof function Summary