Find the number of elements in the array passed as an argument to the function.
I was trying to create a function to find the number of elements in an array. To do this, I turned to the following code:
#include<iostream>
#include<stdlib>
int no_of_ele(A[]) //function to return size of array
{
return (sizeof(A)/sizeof(A[0]);
}
void main()
{
system("cls");
int arr[5] = {1,2,3,4,5};
cout<<"Number of elements in array are "<<no_of_ele(arr)<<endl;
system("pause");
}
In this approach, I got the result like this:
Then I did the following:
cout<<"Size of array is "<<sizeof(arr)<<endl;
cout<<"Size of data type is "<<sizeof(arr[0]);
Now I got absolutely correct size output as follows:
Why?
source to share
On passing to your function, the array decays to a pointer.
sizeof(int)/sizeof(int)... = 1
The reason for this is that parameters are pushed onto the stack for a function. The compiler declared by your function declaration will just send the address of your array.
When passing an array as a parameter
int func(int arr[])
Similar:
int func(int *arr)
By providing an array as an argument to a function, you cannot determine its size with sizeof
.
source to share
There are better ways these days, but the closest:
#include<iostream>
template<std::size_t N>
int no_of_ele(int (&A)[N]){
return sizeof(A)/sizeof(A[0]); // or just return N
}
int main(int argc, char* argv[]){
int arr[5] = {1,2,3,4,5};
std::cout<<"Number of elements in array are "<<no_of_ele(arr)<<std::endl;
return 0;
}
Cheers for 1998. The question is, does Turbo C ++ support templates?
See here for more details: Is it possible to overload a function that can specify a fixed array from a pointer?
source to share