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 size of 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 <bits/stdc++.h>
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 <bits/stdc++.h>
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]   

(&arr + 1) ==> Address of 6 integers ahead as
               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 
                   to the address 6 integers
                   ahead of arr, the difference
                   between two is 6.

This article is contributed by Nikhil Chakravartula from JNTUH College Of Engineering, Hyderabad. In the event that you like GeeksforGeeks and might want to contribute, you can likewise compose an article and mail your article to audit Knittingcut. See your article showing up on the GeeksforGeeks fundamental page and help different Geeks.

Kindly record pieces of feedback assuming you find anything wrong, or you need to share more data about the subject examined previously

Also Read: How to Install OpenCV for Python on Windows?

Leave a Reply

Your email address will not be published. Required fields are marked *