×

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of each element that is the data it is holding is in a continual fashion.

We generally use the pre-defined function the sizeof() to get the length or the size of an array we have declared. Sizeof() function is an underlying smallest unit of code which is being run in the background calculating the array size or the length of the array that we will pass through the sizeof() function. This article will focus on calculating the size of an array without using the sizeof() function in both C and C++ programming languages.

Declaring Arrays in C and C++

Here, we will see how to declare an array in C and C++programming:

Code in C

// writing C program to declare array 
//and printing its output in the console
#include <stdio.h>    
int main()    {    
    //we will write code to initialize array     
    int arr[] = {1, 2, 3, 4, 5};     
    //Calculate length of array    
    int length = 5;    
        
    printf("Elements of the given array are : ");    
    //we will now be looping through the array by incrementing value of i     
    for (int i = 0; i < length; i++) {     
        printf("%d ", arr[i]);     
    }      
     
    return 0;    
}

Output

Elements of the given array are: 1 2 3 4 5

Code in C++

// C++ program to declare array 
//and printing its output in the console
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = 6;
 //we will now be looping through the array by incrementing value of i
    for(int i = 0;i<n;i++){
    cout<<arr[i]<<endl; 
    }
    return 0;
}

Output

1 2 3 4 5 6

C and C++ Code to Find the Size of an Array given by using sizeof() Function

We will find the size of array given by using the sizeof() function in C and C++ programs.

C code

//C code to find the length of an array without sizeof() function
#include<stdio.h>  
 int main()  
{  
    int a[] = {3, 4, 6, 7, 8, 9, 0, 32, 435, 65, 2 };  
  
    int count = sizeof(a) / sizeof(int);  
  
    printf("There are %d no of elements in the array\n", count);  
  
    return 0;  
}

Output

There are 11 no of elements in the array

C++ code

// C++ program to find size of
// an array
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    int size = sizeof(arr)/sizeof(arr[0]);
  
    cout << size;
  
    return 0;
}

Output

6

Finding the Size or Length of Array without using sizeof() Function in both C and C++

As we have seen, an approach in both C and C++ to find the size of an array or the length of an array using the pre-defined size of a function here is the second and even more exciting approach to finding the size of an array using the pointer hack approach. The pointer hack approach is pretty simple and also even very easy to use. As we know that the presence of the concept pointers is what differentiates C and C++ programming languages from other languages such as Python, Java etc., so here to find the length or the size of an array, we are using the pointer hack approach whose syntax and implementation of the code is as follows

Syntax of Pointer Hack Approach

//Assume an example array below
int array[] = {1,2,3,4,5,6,7,8,9}
//syntax for pointer hack approach
int size = *(&array + 1) - array; // &array returns a pointer

C code

//C code to find the length of an array without sizeof() function
#include<stdio.h>  
int main()  
{  
    int arr[] = {32, 422, 226, 444444, 56788, 219, 330, 32, 435, 65,  2, 23,  
               533336, 637, 3338, 3339, 30, 33, 32, 13, 34, 5, 6, 7, 8};  
  
    int size = *(&arr + 1) - arr;
  
    printf("There are about %d number of elements in the array \n", size);  
  
    return 0;  
}

Output

There are about 25 number of elements in the array

C++ code

//C++ code to find the length of an array without sizeof() function
#include <iostream>
using namespace std;
int main() {
   int arr[] = {32, 422, 226, 444444, 56788, 219, 330, 32, 435, 65,  2, 23,  
               533336, 637, 3338, 3339, 30, 33, 32, 13, 34, 5, 6, 7, 8};  
   int s = *(&arr + 1) - arr;
   cout << "Number of elements in array are "<< s;
}

Output

Number of elements in array is 25

Related Topics

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

SDL library in C++ with Examples

SDL stands for Simple DirectMedia Layer. Using OpenGL and Direct3D, it is a cross-platform development library created to give users low-level access to audio, keyboard, mouse, joystick, and graphics hardware....

3 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.