1. Origin
Caused by a question: what is the output of the following code?
Const char * psz = "Hello World ";
Int iarr [] = {1, 2, 3, 4, 5 };
Cout <sizeof (psz) <Endl;
Cout <sizeof (iarr) <Endl;
The former outputs 4 and the psz type, that is, the pointer type occupies 4 bytes (under Win32 ).
The latter output is 20, that is, the length of the array.
I directly saw the answer to this question. I didn't think much about it at first, but later I found that the array name and pointer are very similar, in my opinion, both the array name and psz point to the first address of a string of addresses. How can I calculate sizeof differently?
2. Experiment
According to the information on the Internet, the array name is an object structure that not only contains the first address of the first element of the array, but also the overall length of the array. Therefore, sizeof can obtain the overall length of the array, however, when the array name is passed as a parameter, the actual body feature is gone, just like the pointer.
See the following experiment:
# Include <iostream>
Using namespace STD;
Void F1 (char a []) {
Cout <sizeof (a) <Endl;
}
Void F2 (char * ){
Cout <sizeof (a) <Endl;
}
Int main (){
Char A [] = {'5', '5', '5', '5', '5', '5 '};
Cout <sizeof (a) <Endl; // output 8
F1 (a); // output 4
F2 (a); // output 4
Char * B [1, 100] [2, 100];
Cout <sizeof (B) <Endl; // output 40000
Char wait;
Cin> wait;
Return 0;
}
3. References
C/C ++ array name and pointer difference in-depth exploration http://www.rupeng.com/forum/thread-1533-1-1.html