0

I made a function in C++ to find the length of an array. I find the sizeof the array passed in the argument and divide it by the sizeof the variable type. This should work but it always returns 1! Am I missing something obvious? Or does this have to do with pointers and memory? This is my code:

    #include <iostream>

    using namespace std;

    int lengthOf(int arr[]);

    int main() {
        int x[] = {1,2,3,0,9,8};
        int lenX = lengthOf(x);
        cout << lenX;
        return 0;
    }

    int lengthOf(int arr[]) {
        int totalSize = sizeof arr;
        cout << totalSize << endl;
        int elementSize = sizeof(int);

        return totalSize/elementSize;
    }

Output (should be 6 instead of 1):

    4
    1

I am fairly new so excuse me if this is a bad question.

aanrv
  • 2,159
  • 5
  • 25
  • 37
  • 1
    The thing you're missing is that `int arr[]` becomes `int* arr` as a function parameter. – dyp Sep 14 '13 at 02:53

3 Answers3

1

When passing an array as parameter, it always decays into a pointer. If you want to see the size of the array, you need to pass the array by reference, e.g.:

template <int Size>
int lengthOf(int (&array)[Size]) {
    return Size;
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Which leads to the question ;) why there's `std::extent`, but no function for deducing it in the Standard. (Has it been proposed?) – dyp Sep 14 '13 at 03:02
  • 2
    @DyP: You don't consider `std::extent::value` natural to write? ;-) – Dietmar Kühl Sep 14 '13 at 03:10
0

You should use the pointer.

(sizeof(arr)/sizeof(*arr))

tonyo
  • 678
  • 1
  • 7
  • 22
  • 1
    As far as I know, sizeof(arr) == sizeof(*arr) as the array degenerates into a pointer when passed as an argument. – Sinkingpoint Sep 14 '13 at 02:54
  • @Quirliom In C++, the problem is not the argument (what you pass) but the parameter (what the function expects). The function expects `int arr[]`, which is in that context (function parameter) equivalent to `int* arr`. – dyp Sep 14 '13 at 02:55
  • Correct. You can't pass an array of arbitrary size directly to a function; it decays to a pointer, so sizeof(arr) == sizeof(int*). – cHao Sep 14 '13 at 02:55
  • @DyP Interesting. Thanks for clarifying that. – Sinkingpoint Sep 14 '13 at 02:57
0

Even though int arr[] looks like you are passing an array, you are actually passing a pointer. int arr[] is equivalent to int* arr when used as a function parameter, this comes from C.

In C++, if you want to pass an array, the proper way is to do it by reference:

template <int N>
int lengthOf(int (&arr)[N]) {
     int totalSize = sizeof arr;
     cout << totalSize << endl;
     int elementSize = sizeof(int);

     return totalSize/elementSize;
}
Jesse Good
  • 50,901
  • 14
  • 124
  • 166