Skip to content
Related Articles

Related Articles

How to Find Size of an Array in C/C++ Without Using sizeof() Operator?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 23 May, 2022

In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown:

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

Can we do the same without using the sizeof() operator? 

Given an array (you don’t know the type of elements in the array), find the total number of elements in the array without using the sizeof() operator?

Approach 1: Implement our own sizeof

CPP




// C++ program to find size of
// an array by writing our
// own sizeof operator
#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

Approach 2: Using a pointer hack

 The following solution is very short when compared to the above solution. The number of elements in an array A can be found using the expression:

int size = *(&arr + 1) - arr; // &arr returns a pointer 

CPP




// 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 work? 

Here the pointer arithmetic does its part. We don’t need to explicitly convert each of the locations 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 a pointer to an array of 6 integers. In simple words, (&arr + 1) is the address of integers ahead.
  • *(&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. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!