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?