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?

9
  • How come the output is 2? Commented Jul 24, 2013 at 20:02
  • 1
    If the size of a pointer is twice the size of an int Commented Jul 24, 2013 at 20:02
  • Shouldn't the logic be sizeof(a)/sizeof(a[0])? Commented Jul 24, 2013 at 20:02
  • 3
    @syb0rg, Doesn't matter, really. Commented Jul 24, 2013 at 20:03
  • @syb0rg I am accessing that same element using *a Commented Jul 24, 2013 at 20:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Or use a template, or use std::array.
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.
Thank you. I have used vector and have implemented it correctly.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.