C ++ array name and pointer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.