here is some code
class DengkleTryingToSleep{
public:
int minDucks(int ducks[]);
int temp(int ducks[]){
int size=sizeof(ducks);
cout<<"sizeof="<<size<<"\n";
}
};
int main (int argc, const char * argv[])
{
DengkleTryingToSleep dt;
int arr[]={9,3,6,4};
cout<<"sizeof "<<sizeof(arr);
cout<<"\nsizeof from function "<<dt.temp(arr);
return 0;
}
and output of this is
sizeof 16
sizeof from function sizeof=8
and i have no idea how this is working because it returns 16 (as expected when called inside main)
and returns 8 when called from the function
Actually this function:
is exactly equivalent this function:
There is NO DIFFERENCE at all. No difference. So no matter what you pass, whether an array or a pointer, it will become a pointer inside the function.
That means, when you write
sizeof(ducks)in your function, it is exactly equivalent tosizeof(int*), which returns8on your machine (I guess, your machine has 64-bit OS where the size of pointer is8bytes).If you want to pass an array, and don’t it decay into pointer type, then do this:
Now it will print
16. Note that inside the functionNrepresents the count of items in the array. So in your case, it would be4, as there are4elements in the array. It means, if you need the length of the array, you don’t need to calculate it assizeof(bucks)/sizeof(int), as you already know the length of the array which isN.Also note that there is a limitation in this approach: now you cannot pass dynamically allocated array:
But in C++, you’ve a better option here: use
std::vector<int>.