C++数组求和函数sizeof(u)识别异常的原因与修复咨询
问题原因
在C++里,当数组作为函数参数传递时,数组类型会自动退化为指向其首元素的指针。你写的double u[]作为函数参数,实际上等价于double* u,所以sizeof(u)计算的是指针的大小(64位系统下通常是8字节),而非原数组的总字节数。这就导致sizeof(u)/sizeof(u[0])的结果永远是1,根本没法遍历整个数组。
另外提一句:你代码里的double Uarray[Uarraysize];属于变长数组(VLA),这是C99的特性,C++标准并不支持,属于编译器扩展,移植性很差,不建议使用。
修复方法
方法1:手动传递数组长度(最直接)
调用求和函数时把数组长度传进去,函数内部用这个长度控制遍历:
#include <iostream> using namespace std; double sumArray(double u[], int size) { double summ = 0.0; for(int i = 0; i < size; i++) { summ += u[i]; } return summ; } int main(){ cout << "how big is your array: "; int Uarraysize; cin >> Uarraysize; // 用动态分配替代变长数组,避免编译器扩展依赖 double* Uarray = new double[Uarraysize]; cout << "enter " << Uarraysize << " numbers: " << endl; for(int i = 0; i < Uarraysize; i++){ cin >> Uarray[i]; } double summ = sumArray(Uarray, Uarraysize); cout << "sum: " << summ << endl; delete[] Uarray; // 记得释放动态分配的内存 return 0; }
方法2:模板函数推导数组大小(仅适用于固定大小数组)
如果数组大小是编译期确定的,可以用模板让编译器自动推导数组长度,但这种方式不支持动态输入大小的场景:
#include <iostream> using namespace std; template <size_t N> double sumArray(double (&u)[N]) { double summ = 0.0; for(int i = 0; i < N; i++) { summ += u[i]; } return summ; } int main(){ const int Uarraysize = 5; // 编译期固定大小 double Uarray[Uarraysize]; cout << "enter " << Uarraysize << " numbers: " << endl; for(int i = 0; i < Uarraysize; i++){ cin >> Uarray[i]; } double summ = sumArray(Uarray); cout << "sum: " << summ << endl; return 0; }
方法3:使用std::vector(推荐)
用C++标准库的std::vector替代原生数组,它自带size()方法获取元素个数,还能自动管理内存,完全避免数组退化问题:
#include <iostream> #include <vector> using namespace std; double sumArray(const vector<double>& vec) { double summ = 0.0; // 范围for循环遍历更简洁 for(double num : vec) { summ += num; } return summ; } int main(){ cout << "how big is your array: "; int Uarraysize; cin >> Uarraysize; vector<double> Uarray(Uarraysize); cout << "enter " << Uarraysize << " numbers: " << endl; for(int i = 0; i < Uarraysize; i++){ cin >> Uarray[i]; } double summ = sumArray(Uarray); cout << "sum: " << summ << endl; return 0; }
内容的提问来源于stack exchange,提问作者nick o
相关产品推荐
相关产品推荐

