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:
enter image description here

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:

enter image description here

Why?

+3


source to share


2 answers


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

.

+2


source


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?

+6


source







All Articles