1

I was making a try in passing C++ arrays as arguments in C++ and encountered some problems. I went through this and still wasn't able to solve the problem.

C++
#include<iostream>
using namespace std;

void comb(int a[])
{
    int alen = sizeof(a)/sizeof(*a);
    cout << alen << endl;
    /* Since 'I' know the size of a[] */
    for(int i = 0; i < 7; i++)
    cout << a[i] << " ";
    cout << endl;
}

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

Output
2
1 2 3 4 5 6 7

My question is how come the size of the array is getting calculated as 2?

Community
  • 1
  • 1
Sumit Gera
  • 1,249
  • 4
  • 18
  • 34

2 Answers2

6

When you specify an array as a function argument, it degrades to a pointer. So sizeof(a) is the size of a pointer, not the (byte) size of the array. You'll need to pass the length in as a separate argument, or use something like std::vector.

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
  • 4
    Or use a template, or use `std::array`. – chris Jul 24 '13 at 20:03
  • Or an array reference/pointer. But std::vector should be the default. The 1st rule of arrays is "Don't use arrays". For completion's sake: `void comb(int (&a)[7])` or `void comb(int (*a)[7])`. The `7` can be deduced with a template, as mentioned above. – Átila Neves Jul 24 '13 at 20:36
  • Thank you. I have used vector and have implemented it correctly. – Sumit Gera Jul 24 '13 at 20:54
1

C does not store the length of the array in memory, so the called function has no way of knowing how long the array is.

sizeof is evaluated at compile time, unless you apply it to a array literal, you will not get the length of the array.

You may want to consider passing a std::vector<int> by reference instead.

Andre Holzner
  • 18,333
  • 6
  • 54
  • 63