Sizeof(arr) changes after being passed into a function

Guys I have this little problem here. I have a function that takes an int array as parameter, and in my main() i declare a fixed-size array and pass it into that function, but in that function sizeof(arr) is not the true size. Should be a silly issue. Any advice is greatly appreciated. Below is the code(very straightforward):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <stdlib.h>

using namespace std;

class TriangularNumbers {
public:
  static int missingNumber(int arr[]) 
  {
    int size = 0, sum = 0;
    cout<<"size of array"<<sizeof(arr)<<endl;
    //invalid cases
    if(arr == NULL || ((size = sizeof(arr)/sizeof(arr[0]) )== 1))
      return 0;
    sum = (size + 2)*(size+1)/2;
    for(int i = 0; i < size; i++) {
      cout<<arr[i]<<" ";
      sum -= arr[i];
    }
    cout<<sum<<endl;
    return sum;
  }
};


int main()
{
  int arr[] = {1,4,2,3};

  cout<<"size of array"<<sizeof(arr)<<endl;
  cout<<"missing number: "<<TriangularNumbers::missingNumber(arr)<<endl;

  return 0;
}
Forgot to describe the issue:
In main() it prints "size of array 16" which makes sense, but in missingNumber() it prints "size of array 8".

You have to pass the array size a parameter. You can't rely on sizeof() to give you the size of an unknown array.

FYI, it's because the array is decaying to a pointer.
I see. So there's absolutely no way to pass an array as a parameter without losing any information?

Nope. Use a vector or pass an additional parameter. Personally I'd go with a vector since then you don't have to worry about remembering to pass the parameter.
So there's absolutely no way to pass an array as a parameter without losing any information?

Well, there is, but it is awfully wasteful, you see.

1
2
3
4
5
6
template <size_t N>
int missingNumber(int (&arr)[N])
{
  for (size_t n = 0; n < N; n++)
    ...
}

Hope this helps.
Actually, I didn't think of Duoas's solution at first, but now that he has mentioned that, it can be turned into a proxy/stub/whats-it to the actual function call like this:

1
2
3
4
5
6
7
8
9
10
11
template <size_t N>
inline int missingNumberStub(int (&arr)[N])
{
    return missingNumberActual(N, arr);
}

int missingNumberActual(size_t N, int arr[])
{
  for (size_t n = 0; n < N; n++)
    ...
}

This should alleviate (most of) the wastefulness from instantiating templates when you call missingNumberStub with different arrays.

Regards
Woah, sweet! I didn't think of that!
+1
I don't understand why the template solution would be wasteful?

I don't understand anything that was written in the above codes.
Every time you pass a different size array in you get a whole new function... which is why I like the inline template interface.
Topic archived. No new replies allowed.