Open In App

How to Calculate the Size of a Static Array in C++?

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, static arrays are the type of arrays whose size is fixed, and memory for them is allocated during the compile time. In this article, we will learn how to calculate the size of a static array in C++.

Example:

Input:
myArray = {1, 2, 3, 4, 5}

Output:
The size of the array is 5.

Size of a Static Array in C++

To calculate the size of a static array in C++, we can use the sizeof operator that returns the size of the object in bytes.

Syntax to Find the Size of a Static Array in C++

arraySize = sizeof(arrayName) / sizeof(arrayName[index]);

Here,

  • arrayName is the name of the array.
  • sizeof(arrayName) returns the total size of array in bytes.
  • sizeof(arrayName[index]) returns the size of one element of array.

C++ Program to Calculate the Size of a Static Array

The following program illustrates how we can calculate the size of a static array using the sizeof operator in C++.

C++
// C++ program to illlustrate how to find the size of static
// array
#include <iostream>
using namespace std;

int main()
{
    // Initialize an array
    int arr[] = { 1, 2, 3, 4, 5 };

    // Find the size of the array
    int size = sizeof(arr) / sizeof(arr[0]);

    // Print the size of the array
    cout << "The size of the array is: " << size << endl;

    return 0;
}

Output
The size of the array is: 5

Time complexity: O(1)
Auxiliary space: O(1)




Next Article
Practice Tags :

Similar Reads