Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
Sizeof array passed as parameter
I have this code:
class total {
public:
void display(int []);
};
void total::display(int *arr)
{
int len = sizeof(arr)/sizeof(int);
cout << len;
}
int main(void)
{
int arr[] = { 10, 0, 0, 4, 20 };
total A;
A.display(arr);
return 0;
}
The output is 1 while I expected it to be the length of array , 5
However if I use the sizeof() statement in main() it displays 5.
So, why is the sizeof() not displaying correct value inside the member function?
The sizeof operator returns the size of the operand. In your case
sizeof(arr), the type of the operand isint*. So, the result is either 4 or 8 (depending on the platform, can be also 2 or 1). There is not way to know inside the finction the length of the passed array. Even if you writethis will not change anything because arrays are converted to pointers when they are used as params of the methods. You can still pass array of any size.