# How to find size of array in C/C++ without using sizeof?

Given an exhibit (you dont know the sort of components in the cluster), find the absolute number of components in the exhibit without utilizing sizeof administrator?

// Finds size of arr[] and stores in 'size'
int size = sizeof(arr)/sizeof(arr[0]);

Would we be able to do likewise without utilizing sizeof administrator?

### Technique 1 (Writing our own sizeof)

Given an exhibit (you dont know the sort of components in the cluster), find the absolute number of components in the exhibit without utilizing sizeof administrator?

One arrangement is to compose our own sizeof administrator (See this for subtleties)

 // C++ program to find size of an array by writing our // sizeof #include  using namespace std;   // User defined sizeof macro # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))   int main() {     int  arr[] = {1, 2, 3, 4, 5, 6};     int size = my_sizeof(arr)/my_sizeof(arr[0]);       cout << "Number of elements in arr[] is "          << size;       return 0; }

Output:

Number of elements in arr[] is 6

### Technique 2 (Using a pointer hack)

The accompanying arrangement is extremely short when contrasted with the above arrangement. Number of components in a cluster A can be discovered utilizing the articulation.

int size = *(&arr + 1) - arr;
 // C++ program to find size of an array by using a  // pointer hack. #include  using namespace std;   int main() {     int  arr[] = {1, 2, 3, 4, 5, 6};     int size = *(&arr + 1) - arr;     cout << "Number of elements in arr[] is "          << size;     return 0; }

Output:

Number of elements in arr[] is 6

### How does this function?

Here the pointer number juggling truly does its part. We don’t have to expressly change every one of the areas over to character pointers.

&arr ==> Pointer to an array of 6 elements.
[See this for difference between &arr
and arr]

pointer type is pointer to array
of 6 integers.

*(&arr + 1) ==> Same address as (&arr + 1), but
type of pointer is "int *".

*(&arr + 1) - arr ==> Since *(&arr + 1) points
between two is 6.