Reputation: 51
I found this code , and i m not sure that whether overloading should happen or not.
void print( int (*arr)[6], int size );
void print( int (*arr)[5], int size );
what happens if I pass pointer to an array of 4 elements , to it should come...
any thread will be helpful.
Upvotes: 5
Views: 255
Reputation: 224159
KennyTM's answer is the correct one. Here's an additional thought, though, based on the fact that your question comes with a C++
tag. In C++, you can use templates with non-type arguments to find out array dimensions:
#include <iostream>
template< std::size_t N >
void print(int (&arr)[N]) {std::cout << N << '\n';}
int main()
{
int arr[6];
print(arr);
return 0;
}
Upvotes: 6
Reputation: 1310
The call would be ambiguous as none of the two overloads would be able to convert to int (*arr)[4]
. You need to pass in an element of 5 or 6 elements explicitly.
VS2008 gives:
error C2665: 'print' : none of the 2 overloads could convert all the argument types
(2088): could be 'void print(int (*)[5],int)'
(2093): or 'void print(int (*)[6],int)'
while trying to match the argument list '(int (*)[4], int)'
Hope that helps.
Upvotes: 1
Reputation: 523654
Overloading will happen, and passing the pointer to the array of 4 int
's will not match either function. It's clearer if you write them as the equivalent form:
void print( int arr[][6], int size );
void print( int arr[][5], int size );
An N×4 array can be decayed to a pointer to array of 4 int
's. And it's well known that 2D arrays having different 2nd dimensions are incompatible.
Upvotes: 10