Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of elements in array passed to a function as argument.

I was trying to make a function for finding number of elements in an array. For this I approached for 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 output as follows:
enter image description here

Then, I did this:

cout<<"Size of array is "<<sizeof(arr)<<endl;
cout<<"Size of data type is "<<sizeof(arr[0]);

Now I got absolutely correct output of size as follows:

enter image description here

Why is it?

like image 968
Snigdh Avatar asked Oct 20 '25 15:10

Snigdh


1 Answers

There are better ways these days, but the closest is:

#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;
}

Greetings to 1998. The question is, does Turbo C++ support templates?

See here for more: Is it possible to overload a function that can tell a fixed array from a pointer?

like image 55
alfC Avatar answered Oct 23 '25 05:10

alfC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!