Back to C++
2026-04-267 min read

Get Array Size (C++)

Learn Get Array Size (C++) step by step with clear examples and exercises.

Title: Mastering Array Size in C++ - A full guide

Why This Matters

Understanding how to get the size of an array is crucial for any C++ programmer. It's a fundamental concept that helps you navigate through arrays, manage memory effectively, and avoid common pitfalls like buffer overflows. Knowing the size of an array is essential in various scenarios such as input validation, dynamic memory allocation, and debugging.

Prerequisites

Before diving into the core concept, it's important to have a solid understanding of:

  1. Basic C++ syntax and data structures
  2. Memory management concepts like pointers, arrays, and dynamic memory allocation
  3. Compiler directives like #include and preprocessor macros
  4. Understanding of control statements (if-else, loops)
  5. Familiarity with input/output operations using std::cin and std::cout
  6. Exception handling using try-catch blocks (optional but recommended for robust code)
  7. Understanding of STL containers like vectors, arrays, and tuples
  8. Knowledge of functions and function overloading
  9. Familiarity with classes and objects
  10. Basic understanding of templates

Core Concept

In C++, an array is a collection of elements of the same data type stored in contiguous memory locations. The size of an array is fixed at the time of declaration and cannot be changed during runtime. To access individual elements, you use their index within square brackets [].

int arr[5] = {1, 2, 3, 4, 5}; // Declare and initialize an array with 5 integers
arr[0] = 10; // Access the first element and assign a new value

However, C++ does not provide a built-in function to get the size of an array. To overcome this limitation, you can use various techniques:

Technique 1: Array Length Calculation

The simplest method is to calculate the size of the array by using the array name itself. Since arrays in C++ are treated as pointers to their first element, the size of an array can be obtained by subtracting the address of the first element from the address of the last element and dividing it by the size of one element.

#include <iostream>
using namespace std;

int main() {
int arr[5] = {1, 2, 3, 4, 5};
cout << "Array Size: " << sizeof(arr) / sizeof(arr[0]) << endl;
return 0;
}

Technique 2: Preprocessor Macro

Another approach is to define a preprocessor macro for calculating the size of an array. This method can be useful when dealing with multiple arrays of different sizes within the same codebase.

#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;

int main() {
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[7] = {6, 7, 8, 9, 10, 11, 12};
cout << "Array 1 Size: " << SIZE(arr1) << endl;
cout << "Array 2 Size: " << SIZE(arr2) << endl;
return 0;
}

Technique 3: Using STL (Standard Template Library)

The Standard Template Library provides a std::extent function that can be used to get the size of an array. This technique is more flexible and can handle both built-in arrays and container classes like vectors, arrays, and tuples.

#include <iostream>
#include <array>
using namespace std;

int main() {
array<int, 5> arr = {1, 2, 3, 4, 5};
cout << "Array Size: " << arr.size() << endl;
return 0;
}

Technique 4: Function Overloading

You can create a function that takes an array and its size as arguments to calculate the size of the array. This method allows for greater code reusability and flexibility when dealing with arrays of different sizes.

#include <iostream>
using namespace std;

template<typename T, size_t N>
size_t getArraySize(T(&arr)[N]) {
return N;
}

int main() {
int arr1[5] = {1, 2, 3, 4, 5};
cout << "Array 1 Size: " << getArraySize(arr1) << endl;
int arr2[] = {6, 7, 8, 9, 10, 11, 12};
cout << "Array 2 Size: " << getArraySize(arr2) << endl;
return 0;
}

Worked Example

Let's consider a simple example where we read user input and find the largest number in an array using function overloading and exception handling for invalid input. We will also handle negative numbers and implement exception handling for invalid input.

#include <iostream>
#include <stdexcept>
using namespace std;

template<typename T, size_t N>
T findLargest(T(&arr)[N]) {
T max = arr[0];
for (size_t i = 1; i < N; ++i) {
if (arr[i] > max && arr[i] >= static_cast<T>(MIN_VALUE))
max = arr[i];
else if (arr[i] < static_cast<T>(MIN_VALUE))
throw invalid_argument("Invalid input! Please enter a valid integer.");
}
return max;
}

int main() {
try {
int arr[5];
int n, i;

cout << "Enter the number of elements: ";
cin >> n;

if (n > 5) {
throw runtime_error("Array size exceeded! Please enter a valid size.");
}

cout << "Enter " << n << " integers:" << endl;
for (i = 0; i < n; ++i) {
cin >> arr[i];
if (arr[i] > static_cast<int>(MIN_VALUE)) {
continue;
} else {
throw invalid_argument("Invalid input! Please enter a valid integer.");
}
}

cout << "The largest number is: " << findLargest(arr) << endl;
return 0;
} catch (exception const& e) {
cerr << "Error occurred: " << e.what() << endl;
return 1;
}
}

Common Mistakes

  1. Forgetting to include the necessary headers: Make sure you always include the required header files like ``.
  2. Array bounds out of range: Be careful not to access elements outside the array's valid index range (0 to n-1).
  3. Not handling invalid input: Always validate user input and handle cases where the input exceeds the array size or contains non-numeric values.
  4. Using sizeof() incorrectly: Remember that sizeof(arr) gives the size of the entire array, while sizeof(arr[0]) provides the size of a single element.
  5. Not checking for array overflow: Ensure that the user input does not exceed the maximum array size defined in your code.
  6. Not using exception handling: Implementing exception handling can make your code more robust and easier to debug.
  7. Ignoring the difference between built-in arrays and STL containers: Remember that built-in arrays are not as flexible or feature-rich as STL containers like vectors, arrays, and tuples.
  8. Not considering negative numbers: If your program needs to handle both positive and negative numbers, make sure to include a check for negative values.
  9. Not understanding function overloading: Remember that function overloading allows you to create multiple functions with the same name but different parameters.
  10. Misusing templates: Be careful when using templates to ensure proper type checking and avoid unexpected behavior.

Practice Questions

  1. Write a program to find the second-largest number in an array using function overloading and exception handling for invalid input.
  2. Modify the worked example to handle negative numbers and find the smallest number as well. Implement exception handling for invalid input.
  3. Implement a function that takes an array and its size as arguments and returns the sum of all elements. Use exception handling for invalid input.
  4. Write a program to reverse the order of elements in an array using function overloading and exception handling for invalid input.
  5. Create a program that uses STL containers to find the average of numbers entered by the user until they enter 0. Implement exception handling for invalid input.
  6. Write a function template that calculates the product of all elements in an array. The function should handle arrays of different sizes and data types.
  7. Implement a program that sorts an array using quicksort algorithm and outputs the sorted array. Use exception handling for invalid input.
  8. Modify the worked example to find the median instead of the largest number, assuming the array has an odd number of elements. Implement exception handling for arrays with even numbers of elements.

FAQ

  1. Why can't I use sizeof() directly on an array to get its size?

In C++, sizeof only works on data types and not on variables or expressions that have runtime values. To get the size of an array, you need to use a combination of sizeof and the address operator (&) or calculate it using other techniques like function overloading or preprocessor macros.

  1. What is the difference between built-in arrays and STL containers?

Built-in arrays are simple data structures that store elements of the same type in contiguous memory locations, while STL (Standard Template Library) containers provide more flexible and feature-rich options like vectors, deques, lists, and sets. STL containers offer additional functionality such as dynamic resizing, iterators, and sorting algorithms.

  1. Why should I validate user input?

Validating user input is essential to ensure that your program only processes valid data. Invalid input can lead to unexpected behavior, crashes, or security vulnerabilities. By validating input, you can prevent these issues and make your code more robust.

  1. What are some common mistakes when working with arrays in C++?

Common mistakes include forgetting to include necessary headers, accessing elements outside the array's valid index range, not handling invalid input, using sizeof() incorrectly, not checking for array overflow, ignoring the difference between built-in arrays and STL containers, not considering negative numbers, misusing templates, and not understanding function overloading.

  1. What is exception handling in C++, and why should I use it?

Exception handling is a mechanism that allows your program to handle runtime errors gracefully by catching exceptions (errors) and providing custom error messages or alternative behavior. By using exception handling, you can make your code more robust, easier to debug, and less prone to crashes.

Get Array Size (C++) | C++ | XQA Learn