When passing an array to a function in C++, why won't sizeof() work the same as in the main function?

So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that. I found a question here on stackoverflow that gave this bit of code (sizeof(array)/sizeof(*array)) and while I don't exactly understand it, I understand it takes the total amount of memory allocated to the array and divides it by what I assume is the default memory allocation of its data type...(???) I decided I wanted to practice writing functions (I'm in CS 111 - Fundamentals 1) and write a function that returned the number of elements in any array I passed it. This is what I wrote:

#include <iostream>
using namespace std;

int length_of_array(int some_list[])
{
    // This only returns the integer 1 for some reason
   return (sizeof(some_list)/sizeof(*some_list));
}

int main()
{
    // Declare and initialize an array with 15 elements
    int num_list[] = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30};

    //Outputs what I assume is the total size in bytes of the array
    cout << sizeof(num_list) << endl;

    //Outputs what I assume to be size of memory set aside for each in element in an array
    cout << sizeof(*num_list) << endl;

    //This extrapolates array's number of elements
    cout << "This is the output from direct coding in the\nint main function:\n" <<
            (sizeof(num_list)/sizeof(*num_list)) << endl;

    //This function should return the value 15 but does not
    int length = length_of_array(num_list);

    cout << "This is the length of the array determined\n";
    cout << "by the length_of_array function:\n"  << length << endl;



    return 0;
}

The function returns 1 no matter what I do. Would somebody please give me a C++ specific workaround and explanation of how it works? Thank you.


The problem is here:

int length_of_array(int some_list[]);

Basically, whenever you pass an array as the argument of a function, no matter if you pass it like int arr[] or int arr[42], the array decays to a pointer (with ONE EXCEPTION, see below), so the signature above is equivalent to

int length_of_array(int* some_list);

So of course when doing sizeof(some_list)/sizeof(*some_list) you will get the ratio between the size of the pointer the array decayed to and the size of the type representing the first element. In your case, 1, as it looks like on your machine the size of a pointer is probably 4 bytes (32 bits), same as the size of an int.

So my C++ instructor told us in class that there was no function to determine an array size in C++ and I was not satisfied with that.

YOUR TEACHER IS WRONG! There is a way of passing an array by reference and getting its size:

template<size_t N>
int length_of_array(int (&arr)[N])
{
    std::cout << N << std::endl; // WORKS!
    return N;
}