2

I have written a function size which takes integer array as an argument.

int length(int a[])
{

    return  sizeof(a)/sizeof(int);

}

int main()
{
    int a[] = {1,3,5,6,9,4,2,1,0,0};

    int len = sizeof(a)/sizeof(int);

    cout << len;  // This correctly prints 10 .

    len =  size(a);

    cout << len;  // But this print 2 .why ??

    return 0;
}

Can someone explain me this behaviour? Thanks.

M.M
  • 138,810
  • 21
  • 208
  • 365
Thinker
  • 6,820
  • 9
  • 27
  • 54

2 Answers2

4

The reason you get 2 is because sizeof(int *) is twice as large as sizeof(int), and arrays decay into pointers when passed into a function.

There are various ways to work around this. In C++, you could use a std::vector<int> a = { ... }; instead, which would solve the problem (by calling the a.size() to get the size, as sizeof(a) wouldn't work).

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Or pass the array as `int (&)[N]` – David G Jul 04 '13 at 13:17
  • @Mats can you give me some link regarding std:vector tutorial. I have no idea about that – Thinker Jul 04 '13 at 13:18
  • http://www.cplusplus.com/reference/vector/vector/ Not quite a tutorial, but perhaps a starting point. I'm sure google with "tutorial C++ vector" may give you some other links that at least some may be good - I haven't been "learning" about C++ (at that level at least), so not sure where a good tutorial site is. – Mats Petersson Jul 04 '13 at 13:22
  • @Thinker you should use a good beginners' C++ textbook. Things like `std::vector` are the very basic building blocks of the standard library as part of the language. It's a bread-and-butter `feature` like `double`, for-loops and the like. – Arne Mertz Jul 04 '13 at 13:42
0

Because sizeof(a) is returning the size of the pointer which will be either 4 bytes or 8 bytes depending upon whether your app is 32-bit or 64-bit. So you would need to maintain the length of your array using a separate variable.

Or, better still, I would recommend using one of the standard collection classes, like std::vector for example since this will maintain the length automatically.

Lea Hayes
  • 62,536
  • 16
  • 62
  • 111