Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to print size of array parameter in C++?
Next article icon

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

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Using pointer hack
  2. Using Macro Function
  3. Using own self-made sizeof( )
  4. Using Template Function
  5. Using a Sentinel Value
  6. 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; } 

Output
Number 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 

Output
Number 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; } 

Output
Number 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 

Output
Number 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 

Output
Enter 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 

Output
Enter 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)


Next Article
How to print size of array parameter in C++?
author
kartik
Improve
Article Tags :
  • C++
  • cpp-array
  • cpp-operator
  • cpp-sizeof
Practice Tags :
  • CPP
  • cpp-operator

Similar Reads

  • How to sort an Array using STL in C++?
    Given an array arr[], sort this array using STL in C++. Example: Input: arr[] = {1, 45, 54, 71, 76, 12} Output: {1, 12, 45, 54, 71, 76} Input: arr[] = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12} Approach: Sorting can be done with the help of sort() function provided in STL. Syntax: sort(arr, arr
    1 min read
  • How to print size of array parameter in C++?
    How to compute the size of an array CPP? C/C++ Code // A C++ program to show that it is wrong to  // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize(int arr[]) { cout << sizeof(arr) << endl; } int main() { int a[10]; cout <
    3 min read
  • Do Not Use sizeof For Array Parameters in C
    Using sizeof directly to find the size of arrays can result in an error in the code, as array parameters are treated as pointers. Consider the below program. C/C++ Code // C Program to demonstrate incorrect usage of sizeof() for // arrays #include <stdio.h> void fun(int arr[]) { int i; // size
    4 min read
  • How to declare a 2D array dynamically in C++ using new operator
    Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[si
    4 min read
  • How to print dimensions of multidimensional array in C++
    Create a function that prints multidimensional array size by dimensions i.e.:Examples: Input : int a[2][3][4]; printDimensions(a); Output : 2x3x4 Input : int b[5][6]; printDimensions(a); Output : 5x6 To solve this problem we should use template function to figure out the size of current array. Then
    2 min read
  • How to pass a 2D array as a parameter in C?
    A 2D array is essentially an array of arrays, where each element of the main array holds another array. In this article, we will see how to pass a 2D array to a function. The simplest and most common method to pass 2D array to a function is by specifying the parameter as 2D array with row size and c
    3 min read
  • array::operator[ ] in C++ STL
    Array classes are generally more efficient, light-weight, and reliable than C-style arrays. The introduction of array class from C++11 has offered a better alternative for C-style arrays. array::operator[] This operator is used to reference the element present at position given inside the operator.
    2 min read
  • 5 Different Methods to Find Length of a String in C++
    The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type. Examples: Input: "Geeksforgeeks" Output: 13 Input: "Geeksforgeeks \0 345" Output: 1
    4 min read
  • Pointer to an Array in C++
    Pointers in C++ are variables that store the address of another variable while arrays are the data structure that stores the data in contiguous memory locations. In C++, we can manipulate arrays by using pointers to them. These kinds of pointers that point to the arrays are called array pointers or
    6 min read
  • Convert given Binary Array to String in C++ with Examples
    Given a binary array arr[] containing N integer elements, the task is to create a string s which contains all N elements at the same indices as they were in array arr[]. Example: Input: arr[] = {0, 1, 0, 1}Output: string = "0101" Input: arr[] = { 1, 1, 0, 0, 1, 1}Output: string = "110011" Different
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences