【问题标题】:Why does the sizeof operator return the wrong value when used on an array passed to a method? [duplicate]为什么 sizeof 运算符在传递给方法的数组上使用时返回错误的值? [复制]
【发布时间】:2015-02-04 13:18:24
【问题描述】:
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 作为答案。 谁能帮我解决这个问题。

C++初学者

【问题讨论】:

标签: c++


【解决方案1】:

函数中的sizeof(arr1) 返回指针的大小,而不是整个数组的大小。
语言就是这样。

您必须在没有sizeof 的情况下确定数组大小:
要么传递带有数字的第二个参数,要么以某种方式填充数组
你可以找到终点,因为那里有一个特定的价值(而且没有其他地方)

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多