我对C ++很新。从示例中,我发现使用sizeof
来检索数组的长度
int main()
{
int newdens[10];
// the first line returns 10 which is correct
std::cout << "\nLength of array = " << (sizeof(v1)/sizeof(*v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(v1) << std::endl; //returns 40
std::cout << "\nLength of array = " << (sizeof(*v1)) << std::endl; //returns 4
}
但如果我写了这样的函数
#include <iostream>
void myCounter(int v1[])
{
int L, L2, L3;
L = (sizeof(v1)/sizeof(*v1));
L2 = (sizeof(v1));
L3 = (sizeof(*v1));
std::cout << "\nLength of array = " << L << std::endl;
std::cout << "\nLength of array = " << L2 << std::endl;
std::cout << "\nLength of array = " << L3 << std::endl;
}
int main()
{
int v1[10];
std::cout << "\nLength of array = " << (sizeof(v1)/sizeof(*v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(v1)) << std::endl;
std::cout << "\nLength of array = " << (sizeof(*v1)) << std::endl;
myCounter(v1);
}
输出L = 2,L2 = 8,L3 = 4.我无法理解问题所在。
如何在函数内检索v1的正确长度?
答案 0 :(得分:2)
这里的问题是sizeof()
在编译时解决了。因为它没有关于你的数组有多大的信息,所以它无法分辨它的大小。它将它解释为指向int的指针,在您的机器上为64位。
最好的方法是使用std :: vector而不是C风格的数组,并使用其方法size()
。