I. sizeof
Sizeof (...) is an operator. In the header file, typedef is an unsigned Int. Its value is calculated after compilation. The parameter can be an array, pointer, type, object, function, etc.
Its function is to obtain the maximum object size that can be accommodated.
Because it is calculated during compilation, sizeof cannot be used to return the size of the dynamically allocated memory space. In fact, sizeof is used to return the type and space occupied by objects, structures, or arrays statically allocated. The returned value has nothing to do with the content stored by objects, structures, and arrays.
Specifically, when the parameters are as follows, the values returned by sizeof are as follows:
Array -- size of the array space allocated during compilation;
Pointer -- size of the space used to store the pointer (the address length of the pointer, which is a long integer and should be 4 );
Type -- the space occupied by this type;
Object-the actual space occupied by the object;
Function: the space occupied by the return type of the function. The return type of the function cannot be void.
Ii. strlen
Strlen (...) is a function that can be computed only at runtime. The parameter must be a character pointer (char *). When the array name is passed in as a parameter, the array actually degrades to a pointer.
Its function is to return the length of a string. The string may be defined by itself or randomly stored in the memory. The function is actually used to traverse from the first address representing the string until the end character is null. The returned length does not include null.
Iii. Example:
Eg1, char arr [10] = "what? ";
Int len_one = strlen (ARR );
Int len_two = sizeof (ARR );
Cout <len_one <"and" <len_two <Endl;
Output result: 5 and 10
Comment: When sizeof returns the definition arr array, the size of the array space allocated by the compiler does not care how much data is stored in it. Strlen only cares about the stored data content and does not care about the size and type of the space.
Eg2, char * Parr = new char [10];
Int len_one = strlen (Parr );
Int len_two = sizeof (Parr );
Int len_three = sizeof (* Parr );
Cout <len_one <"and" <len_two <"and" <len_three <Endl;
Output result: 23 and 4 and 1
Comment: The first output result 23 may be different each time it is run, depending on what is stored in the Parr (from Parr [0] to know that the first null is ended ); the second result is actually intended to calculate the size of the dynamic memory space that Parr points to, but it is counterproductive. sizeof considers Parr as a character pointer, therefore, the returned result is the space occupied by the pointer (the pointer is stored in a long integer, so it is 4). The third result is, because * Parr represents the characters in the address space indicated by Parr, the length is 1.
Differences and relationships between sizeof and strlen