How can I find the number of elements in an array?

AndrewP picture AndrewP · Apr 24, 2012 · Viewed 239.5k times · Source

I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I'm not sure how to use it exactly.

Answer

Pavel Zhuravlev picture Pavel Zhuravlev · Apr 24, 2012

If you have your array in scope you can use sizeof to determine its size in bytes and use the division to calculate the number of elements:

#define NUM_OF_ELEMS 10
int arr[NUM_OF_ELEMS];
size_t NumberOfElements = sizeof(arr)/sizeof(arr[0]);

If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof. You'll have to store/pass the size information somehow to be able to use it:

void DoSomethingWithArray(int* arr, int NumOfElems)
{
    for(int i = 0; i < NumOfElems; ++i) {
        arr[i] = /*...*/
    }
}