Arrays and pointers in C + +

Source: Internet
Author: User

The first thing to make clear is that the array type and pointer type are really different types!

Char *p; Type is char*

Char str[6];//type is char [6]

Type information can be output using the following statement (requires #include<typeinfo>)

Std::cout << typeid (P). Name () << Std::endl;
Std::cout << typeid (str). Name () << Std::endl;

But sometimes we always define a function like this:

void foo (char *p) {

cout << p << Endl;

cout << sizeof (p)/sizeof (char); Output is 4

}

We found that we dropped Str in and it worked. So to be taken for granted, I define a function like this:

void foo (char str[6]) {

cout << str << Endl;

cout << sizeof (str)/sizeof (char) << endl;//output is also 4

}

We found that the input p is not a problem, there is a problem, and the second output is confusing, according to the type information it should output 6.

The problem here is that when you use a non-reference type as a formal parameter, the array type is automatically dropped to the pointer type to handle , that is, Foo (char str[6]) is exactly the same as Foo (char *p)!

To illustrate this point of knowledge, we changed the function prototype to the following:

void foo (char (&STR) [6]) {

cout << str << Endl;

cout << sizeof (str)/sizeof (char) << endl;//output to 6

}

At this point, we find that only the input char[6] type can be compiled, and the second output is 6, that is, the array length information is normally preserved during the parameter transfer.

When a reference type is a parameter, the array type does not fall to the pointer type!

Finally, based on this, we can write a function that takes an array of any dimension as a parameter, of course, using a template, because arrays of different lengths belong to different types:

Template<int N, int m>
int foo (int const (&A) [n][m], int const (&B) [n][m]) {
Std::cout << typeID (a). Name () << Std::endl; Output INT[N][M]
return 0;
}

Arrays and pointers in C + +

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.