At first, my problem was:
Char intarray [] = "wo Shi shui ";
Int Len = sizeof intarray;
Cout <Len <Endl;
The output is 12.
Char * intarray = "wo Shi shui ";
Int Len = sizeof intarray;
Cout <Len <Endl;
Output is 4
Why is one output 12 and one output 4. because I think that the length of this string can be obtained through sizeof and a string pointer through conditional reflection, but as shown above, A pointer cannot obtain the length of a string. Only the number of bytes of the pointer can be returned.
Cause: I personally think that the pointer is a variable and cannot use sizeof to obtain the length of a variable. Therefore, only the length of the variable type can be obtained.
Below are the columns on msdn.
Sizeof:SizeofOperator yields the size of its operand with respect to the size of TypeChar
WhenSizeofOperator is applied to an object of TypeChar, It yields 1. WhenSizeofOperator is applied to an array, it yields the total number of bytes in that array, not the size of the pointer represented by the array identifier. to obtain the size of the pointer represented by the array identifier, pass it as a parameter to a function that usesSizeof
# Include <iostream>
Size_t getPtrSize (char * ptr)
{
Return sizeof (ptr );
}
Using namespace std;
Int main ()
{
Char szHello [] = "Hello, world! ";
Cout <"The size of a char is :"
<Sizeof (char)
<"/NThe length of" <szHello <"is :"
<Sizeof szHello
<"/NThe size of the pointer is"
<GetPtrSize (szHello) <endl;
}
Output
The size of a char is: 1
The length of Hello, world! Is: 14
The size of the pointer is 4
The above are all references on MSDN
The sizeof operation can be used to obtain the size of the char-type operand.
When sizeof is used to operate the char object, it returns 1. When sizeof is applied to the array, it returns the number of bytes of the entire array, instead of the number of bytes used to define the array pointer (that is, the number of bytes is not the pointer type, in 32-bit OS, the pointer's byte tree is 4), and the pointer size can be obtained using the pointer as a parameter.