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)?