How to Find Size of an Array in C++ Without Using sizeof() Operator?
Last Updated :
11 Oct, 2024
In C++, generally, we use the sizeof() operator to find the size of arrays. But there are also some other ways using which we can find the size of an array. In this article, we will discuss some methods to determine the array size in C++ without using sizeof() operator.
Methods to Find the Size of an Array without Using 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. The C++ Course provides practical methods to achieve this, enhancing your understanding of array handling. So, we can use the methods mentioned below:
- Using pointer hack
- Using Macro Function
- Using own self-made sizeof( )
- Using Template Function
- Using a Sentinel Value
- Using a Class or Struct
1. Using 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 Method 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) - After adding 1 to the address of array of 6 integers, the pointer will point to the memory location immediately after the end of the array.
- *(&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.
C++ Program to Find the Size of an Array Using Pointer Hack
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;
}
OutputNumber of elements in arr[] is 6
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
2. Using Macro Function
We can define a macro that calculates the size of an array based on its type and the number of elements.
#define array_size(arr) (sizeof(arr) / sizeof(*(arr)))
- array_size(arr): Name of the macro
- (sizeof(arr): size of entire array in bytes
- sizeof(*(arr)): size of single element in bytes
Dividing the total size of the array by the size of a single element gives the number of elements in the array.
C++ Program to Find the Size of an Array using Macro
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
OutputNumber of elements in arr[] is 6
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
3. Implement Our Own sizeof( )
Using custom user-defined sizeof function which can provide the functionality same as sizeof( ).
C++ Program to Implement Custom User-Defined sizeof Function
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;
}
OutputNumber of elements in arr[] is 6
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
To know more about the method refer to Implement our own sizeof.
4. Using Template Function
We can use a template function to find the size of an array.
C++ program to Find the Size of an Array Using Template Function
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
OutputNumber of elements in arr[] is 6
Explanation
The array_size() function is a template function that takes two parameters:
- T: Type of array elements
- N: Size of the array
The parameter T (&arr)[N] means the function accepts a reference to any type and any size of array. When array_size function is called with the array name as parameter, T is deduced as int and N is deduced as 6.
Complexity Analysis
- Time complexity: O(1)
- Auxiliary space: O(1)
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.
C++ program to Find the Size of an Array using a Sentinel Value
C++
// C++ program to find size of
// an array using sentinel value
#include <iostream>
using namespace std;
int main()
{
// maximum size of the array
const int MAX_SIZE = 100;
// declare the array
int arr[MAX_SIZE];
// sentinel value to indicate the end
// of the array
int sentinel = -1;
// 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];
// exit the loop if the sentinel value is
// entered
if (arr[i] == sentinel) {
break;
}
i++;
}
// calculate the size of the array
// the size of the array is the number of
// elements entered
int size = i;
// print the size of the array
cout << "Size of the array: " << size << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
OutputEnter a value for element 0 (or -1 to stop): Enter a value for element 1 (or -1 to stop): Enter a value for element 2 (or -1 to stop): Enter a value for element 3 (or -1 to stop): Enter a value for el...
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
Complexity Analysis
- Time complexity: O(n), where n is the number of elements in the array.
- Auxiliary space: O(1)
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.
C++ program to Find the Size of an Array using a Class and Member Function
C++
// C++ program to find size of
// an array usinga Class or Struct
#include <iostream>
using namespace std;
class MyArray {
private:
// declare the array
int arr[100];
// size of the array
int size;
public:
// read values into the array
void readArray();
// get the size of the array
int getSize();
};
void MyArray::readArray()
{
// initialize size to 0
size = 0;
while (size < 100) {
cout << "Enter a value for element " << size
<< " (or -1 to stop): ";
cin >> arr[size];
// exit the loop if -1 is entered
if (arr[size] == -1) {
break;
}
// increment size for each element entered
size++;
}
}
int MyArray::getSize()
{
// return the size of the array
return size;
}
int main()
{
// declare an object of MyArray
MyArray a;
// read values into the array
a.readArray();
// get the size of the array
int size = a.getSize();
// print the size of the array
cout << "Size of the array: " << size << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
OutputEnter a value for element 0 (or -1 to stop): Enter a value for element 1 (or -1 to stop): Enter a value for element 2 (or -1 to stop): Enter a value for element 3 (or -1 to stop): Enter a value for el...
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
Complexity Analysis
- Time complexity: O(1), getSize() method returns size member variable that takes constant time.
- Auxiliary space: O(1)
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Vector in C++ STL
C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
30 OOPs Interview Questions and Answers [2025 Updated]
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Templates in C++
C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read
C++ Polymorphism
The word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is ca
5 min read
C++ Interview Questions and Answers (2025)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read