0

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?

Community
  • 1
  • 1
Jatin
  • 14,112
  • 16
  • 49
  • 78
  • http://c-faq.com/aryptr/aryparmsize.html – cnicutar Jul 01 '12 at 09:34
  • @Jatin first, advice, forget about (raw) pointers and arrays. They are not used anymore, as we have shared_ptr and vector instead. That's XXI century. Use XXI century tools. Second, in your you get one because sizeof(arr) gets size of ptr which is 4, and sizeof(int) gives you 4. 4/4 == 1. Good luck. – smallB Jul 01 '12 at 09:37
  • @smallB, I would not agree with your advice. These good tools should be used when it is already clear how to work with pointers. I have no doubt that Jatin will come to that stage. Plus there are tons of situations when the size of array is fixed, etc. Hammer is an old fashioned but it is still extremely useful tool. – Kirill Kobelev Jul 01 '12 at 09:56
  • @KirillKobelev you may not agree with me, but according to Bjarne that's the best way to learn modern C++. In other words: You don't have to nor should you know/learn first how car's engine works just to be able to learn how to drive a car. – smallB Jul 01 '12 at 10:10

2 Answers2

3

sizeof of an array operand yields the size of the array but sizeof of a pointer operand yields the size of the pointer. Pointer and arrays are not the same in C/C++.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

The sizeof operator returns the size of the operand. In your case sizeof(arr), the type of the operand is int*. 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 write

void total::display(int arr[5])
{
}

this 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.

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51