如何使用
sizeof()
来确定数组引用的大小?
我在
main()
中声明了一个数组,并使用 sizeof()
打印它所占用的总大小。
然后我将数组传递给函数作为对数组的引用,但我无法使用
sizeof()
作为引用(数组)变量。
#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)
显示编译器错误:
error: invalid application of ‘sizeof’ to incomplete type ‘double []’
std::cout << "the size is : " << sizeof(list) << std::endl;
将函数参数更改为
double (&list)[6]
后,我得到了我想要的输出,但是当 sizeof(list)
声明时没有明确提及其大小(尽管它是一个引用)时,为什么 sizeof(arr)
不像 list
那样工作?
C 风格数组的大小是其类型的一部分,因此声明为
double arr[6];
的数组具有类型 (double)[6].
,这是一个完整的类型。
sizeof
运算符在编译时工作。当您在数组上使用 sizeof
时,它会返回数组的大小(以字节为单位)。这是可能的,因为数组的大小是其类型的一部分,并且编译器在编译时知道它。
但是,如果您尝试在不完整的类型上使用
sizeof
,这将导致编译错误,因为 sizeof
的参数类型必须是完整的。