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

后端 未结 1 1944
無奈伤痛
無奈伤痛 2020-12-02 01:30

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 stackoverflo

相关标签:
1条回答
  • 2020-12-02 01:56

    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;
    }
    
    0 讨论(0)
提交回复
热议问题