在传递给方法的数组上使用sizeof运算符时,为什么返回错误的值? [英] Why does the sizeof operator return the wrong value when used on an array passed to a method?
本文介绍了在传递给方法的数组上使用sizeof运算符时,为什么返回错误的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int size(int arr1[])
{
int size1=sizeof(arr1)/sizeof(int);
cout<<size1<<endl;
return size1;
}
void main()
{
int b[]={1,2,3,4,5};
int size2 = size(b);
cout<<size2<<endl;
for (int i=0;i<size2;i++)
{
cout<<b[i];
}
}
我将b []函数放入size()并检查大小,然后返回值.但是,它只返回1作为答案.谁能帮我解决这个问题.
I have put the b[] function into size() and check the size then return value. however, it just return 1 as the answer. Can anyone please help me to solve this.
C ++的初学者
推荐答案
sizeof(arr1)
返回指针的大小,而不是整个数组的大小.
语言就是这样.
sizeof(arr1)
in the function returns the size of a pointer, not of the whole array.
That´s just how the language is.
您必须在不使用 sizeof
的情况下确定数组大小:
传递带有数字的第二个参数,或以某种方式填充数组
您可以找到终点,因为那里有一个特定的值
You´ve to determine the array size without sizeof
:
Either pass a second parameter with the number, or fill the array in a way
you can find the end because a certain value is there (and nowhere else)
这篇关于在传递给方法的数组上使用sizeof运算符时,为什么返回错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文