Search code examples
c++arrayspass-by-reference

how to use sizeof() for reference_to_array in c++


How to use sizeof() to determine the size of a reference to an array?

I have declared an array in main() and used sizeof() to print its total size it has occupied.

And then I pass the array to a function as a reference to the array, but I am unable to use sizeof() for the reference (array) variable.

#include <iostream>

double sum(double (&list)[], size_t size);

int main(){
    double arr[]{34.5, 67.8, 92.345, 8.1234, 12.314, 3.4};
    double result{};

    std::cout << "size of the array : " << sizeof(arr) << std::endl;
    result = sum(arr, std::size(arr));
    std::cout << "the total is " << result << std::endl;
    
    return 0;
}

double sum(double (&list)[], size_t size){
    double total{};
    std::cout << "the size is : " << sizeof(list) << std::endl;

    for( int i{} ; i < size ; i++){
        total += list[i];
    }
    
    return total;
}

sizeof(list) shows a compiler error:

error: invalid application of ‘sizeof’ to incomplete type ‘double []’
     std::cout << "the size is : " << sizeof(list) << std::endl;

After changing the function parameter as double (&list)[6] I get the output I want, but why is sizeof(list) not working like sizeof(arr) when list is declared without explicitly mentioning its size in the declaration, though it's a reference?


Solution

  • The size of a C-style array is part of its type, so an array declared as double arr[6]; has type (double)[6]. which is a complete type.

    The sizeof operator works at compile-time. When you use sizeof on an array, it returns the size of the array in bytes. This is possible because the size of the array is part of its type and the compiler knows it at compile time.

    However, if you attempt to use sizeof on an incomplete type such as (double)[], this will result in compilation error, as the type of the argument to sizeof has to be complete.