Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In C++, we use the 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]);

Methods to Find the Size of an Array 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. So, we can use the methods mentioned below:

  1. Using pointer hack
  2. Using own self-made sizeof( )
  3. Using Template Function
  4. Using Macro Function
  5. Using a Sentinel Value
  6. Using a Class or Struct

1. Using a Pointer Hack

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

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

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.

Example:

C++




// C++ program to find size
// of an array by using a
// pointer hack
#include <iostream>
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

2. Implement our own sizeof( ):

Using custom user-defined sizeof function which can provide the functionality same as sizeof( ).

Example:

C++




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

To know more about the method refer to Implement our own sizeof.

3. Using Template Function:

We can use a template function to find the size of an array.

Example:

C++




// C++ program to find size of
// an array using Template Function
#include <bits/stdc++.h>
using namespace std;
 
// Calculating size of an array
template <typename T, size_t N>
 
int array_size(T (&arr)[N])
{
    return N;
}
 
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int size = array_size(arr);
    cout << "Number of elements in arr[] is " << size;
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

Number of elements in arr[] is 6

4. Using Macro Function:

We can define a macro that calculates the size of an array based on its type and the number of elements.

Example:

C++




// C++ program to find size of
// an array using Macro Function
#include <bits/stdc++.h>
using namespace std;
 
// Defining Macro
#define array_size(arr) (sizeof(arr) / sizeof(*(arr)))
 
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int size = array_size(arr);
    cout << "Number of elements in arr[] is " << size;
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

Number of elements in arr[] is 6

5. Using a Sentinel Value:

We can add a special value to the end of the array to indicate the end of the array, and then loop through the array until you find the sentinel value. This method is commonly used in string manipulation.

Example:

C++




// C++ program to find size of
// an array using sentinel value
#include <iostream>
using namespace std;
 
int main()
{
    const int MAX_SIZE = 100; // maximum size of the array
    int arr[MAX_SIZE]; // declare the array
    int sentinel = -1; // sentinel value to indicate the end
                       // of the array
 
    // read values into the array until the sentinel value
    // is entered
    int i = 0; // counter variable
    while (i < MAX_SIZE) {
        cout << "Enter a value for element " << i
             << " (or -1 to stop): ";
        cin >> arr[i];
        if (arr[i] == sentinel) {
            break; // exit the loop if the sentinel value is
                   // entered
        }
        i++;
    }
 
    // calculate the size of the array
    int size = i; // the size of the array is the number of
                  // elements entered
 
    // print the size of the array
    cout << "Size of the array: " << size << endl;
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output

Enter a value for element 0 (or -1 to stop): 3
Enter a value for element 1 (or -1 to stop): 7
Enter a value for element 2 (or -1 to stop): 2
Enter a value for element 3 (or -1 to stop): 9
Enter a value for element 4 (or -1 to stop): 5
Enter a value for element 5 (or -1 to stop): -1
Size of the array: 5

6. Using a Class or Struct:

We can define a class or struct that contains an array as a member variable, and then define a member function that returns the size of the array. This method is useful if we need to pass the array and its size as a single parameter to a function.

Example:

C++




// C++ program to find size of
// an array usinga Class or Struct
#include <iostream>
using namespace std;
 
class MyArray {
    private:
        int arr[100]; // declare the array
        int size; // size of the array
    public:
        void readArray(); // read values into the array
        int getSize(); // get the size of the array
};
 
void MyArray::readArray() {
    size = 0; // initialize size to 0
    while (size < 100) {
        cout << "Enter a value for element " << size << " (or -1 to stop): ";
        cin >> arr[size];
        if (arr[size] == -1) {
            break; // exit the loop if -1 is entered
        }
        size++; // increment size for each element entered
    }
}
 
int MyArray::getSize() {
    return size; // return the size of the array
}
 
int main() {
    MyArray a; // declare an object of MyArray
    a.readArray(); // read values into the array
    int size = a.getSize(); // get the size of the array
    cout << "Size of the array: " << size << endl; // print the size of the array
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Output:

Enter a value for element 0 (or -1 to stop): 8
Enter a value for element 1 (or -1 to stop): 4
Enter a value for element 2 (or -1 to stop): 2
Enter a value for element 3 (or -1 to stop): 7
Enter a value for element 4 (or -1 to stop): 5
Enter a value for element 5 (or -1 to stop): 6
Enter a value for element 6 (or -1 to stop): -1
Size of the array: 6

My Personal Notes arrow_drop_up
Last Updated : 31 Mar, 2023
Like Article
Save Article
Similar Reads