0

I don't understand the difference between this code:

void display(int arr[])
{
    int size=sizeof(arr)/sizeof(arr[0]);
    cout<<"Size: "<<size<<endl;
    for (int i=0; i<size; i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}

int main()
{
    int arr[]={8, 3, 2, 5};
    display(arr);
}

Which gives output:

Size: 1
8

And this code

void display(int arr[], int size)
{
    for (int i=0; i<size; i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}

int main()
{
    int arr[]={8, 3, 2, 5};
    int size=sizeof(arr)/sizeof(arr[0]);
    cout<<"Size: "<<size<<endl;
    display(arr, size);
}

And the output is:

Size: 4
8 3 2 5

Logically it does the same thing, the difference is that size is passed by value, not calculated inside a function. How can I fix this (how to pass only array and calculate size inside a display function)? Or why it isn't possible (with my low understanding of pointers)?

Pulpit
  • 85
  • 7
  • 3
    the array parameter is decayed to a pointer, so the size is lost - tale as old as time, 100s of duplicates. – underscore_d Oct 26 '20 at 15:51
  • or https://stackoverflow.com/questions/1975128/why-isnt-the-size-of-an-array-parameter-the-same-as-within-main or https://stackoverflow.com/questions/1328223/when-a-function-has-a-specific-size-array-parameter-why-is-it-replaced-with-a-p or etc. – underscore_d Oct 26 '20 at 15:54
  • 2
    Use a `std::array` or `std::vector` to overcome this problem. – πάντα ῥεῖ Oct 26 '20 at 15:56

0 Answers0