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 + +