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.

1
  • 1
    The thing you're missing is that int arr[] becomes int* arr as a function parameter. Commented Sep 14, 2013 at 2:53

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Which leads to the question ;) why there's std::extent, but no function for deducing it in the Standard. (Has it been proposed?)
@DyP: You don't consider std::extent<decltype(array)>::value natural to write? ;-)
0

You should use the pointer.

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

3 Comments

As far as I know, sizeof(arr) == sizeof(*arr) as the array degenerates into a pointer when passed as an argument.
@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.
Correct. You can't pass an array of arbitrary size directly to a function; it decays to a pointer, so sizeof(arr) == sizeof(int*).
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;
}

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.