为何C++中数组作为函数参数时sizeof返回8字节而非4字节?
数组作为函数参数时sizeof返回指针大小的原因及解决方法
你遇到的问题核心是C++中数组作为函数参数传递时会自动退化为指向首元素的指针,而非你以为的“首元素引用”。
问题分析
- 在
main函数中,A是真正的数组类型,sizeof(A)计算的是整个数组的总字节数:5个int元素 × 4字节/元素 = 20字节,这和你的预期一致。 - 但当你把数组传入
sumOfElements函数时,参数int A[]会被编译器解析为int* A(指针类型)。在64位系统中,指针的大小是8字节,所以sizeof(A)返回8;如果是32位系统则会返回4字节,这就是你预期和实际结果不符的原因。 - 函数里的
sizeof(A)/sizeof(A[0])计算完全错误,它得到的是8/4=2,循环只会执行2次,最终求和结果是1+2=3,而非数组全部元素的和。
解决方法
如果需要在函数中获取数组的真实大小,有几种可靠的方式:
1. 手动传递数组大小作为参数
直接把数组的长度传给函数,这是最直接的C风格解决方案:
#include <iostream> using namespace std; int sumOfElements(int A[], int size) { int i, sum = 0; cout << "Size of A (pointer) " << sizeof(A) << endl; cout << "Size of A[0] " << sizeof(A[0]) << endl; for (i = 0; i < size; i++) { sum += A[i]; } return sum; } int main() { int A[] = {1, 2, 3, 4, 5}; int size = sizeof(A)/sizeof(A[0]); int total = sumOfElements(A, size); cout << "Sum of elements = " << total << endl; cout << "Size of A (array) " << sizeof(A) << endl; cout << "Size of A[0] " << sizeof(A[0]) << endl; return 0; }
2. 使用std::array替代C风格数组
std::array是C++标准库提供的容器,它不会退化为指针,能保留自身的大小信息:
#include <iostream> #include <array> using namespace std; int sumOfElements(const array<int, 5>& A) { int sum = 0; cout << "Size of A (std::array) " << sizeof(A) << endl; cout << "Size of A[0] " << sizeof(A[0]) << endl; for (int num : A) { sum += num; } return sum; } int main() { array<int, 5> A = {1, 2, 3, 4, 5}; int total = sumOfElements(A); cout << "Sum of elements = " << total << endl; cout << "Size of A (std::array) " << sizeof(A) << endl; cout << "Size of A[0] " << sizeof(A[0]) << endl; return 0; }
3. 使用模板函数推导数组大小
通过模板参数自动推导数组的长度,避免手动传递大小:
#include <iostream> using namespace std; template <size_t N> int sumOfElements(int (&A)[N]) { int sum = 0; cout << "Size of A (array reference) " << sizeof(A) << endl; cout << "Size of A[0] " << sizeof(A[0]) << endl; for (size_t i = 0; i < N; i++) { sum += A[i]; } return sum; } int main() { int A[] = {1, 2, 3, 4, 5}; int total = sumOfElements(A); cout << "Sum of elements = " << total << endl; cout << "Size of A (array) " << sizeof(A) << endl; cout << "Size of A[0] " << sizeof(A[0]) << endl; return 0; }
内容的提问来源于stack exchange,提问作者Jabid Hasan
相关产品推荐
相关产品推荐

