Tutorials  /  Linux Basics

How to Determine the Length of an Array in C++

Ccentron Redaktion · November 2024 ·4 min read ·Linux Basics, Tutorial

Introduction

Understanding how to determine the length of an array in C++ is essential when working with arrays. The length of an array refers to the total number of elements it contains. For example:

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Code
int array1[] = {0, 1, 2, 3, 4};

The length of this array is 5, as it contains five elements. In this article, we explore various methods to calculate the length of an array in C++ with clear examples.

Methods to Determine Array Length

There are several approaches to calculate the length of an array in C++. These include:

  1. Counting each element
  2. Using begin() and end()
  3. Using the sizeof() function
  4. Leveraging the size() method from STL
  5. Using pointers

Each method is described in detail below.

1. Counting Each Element

By iterating through the array and counting each element, we can determine its length. This approach is straightforward and uses a for-each loop. Below is an example:

Code
#include
using namespace std;

int main() {
    int count = 0;
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    cout << "The array is: ";
    for (auto i : arr) {
        cout << i << " ";
        count++;
    }
    cout << "\nThe length of the given array is: " << count;
    return 0;
}

Output:

Code
The array is: 1 2 3 4 5 6 7 8 9 0
The length of the given array is: 10

Here, the for-each loop iterates through the array and increments the count variable on each iteration. After the loop completes, count contains the total number of elements in the array.

2. Using begin() and end()

The begin() and end() functions from the C++ Standard Library provide iterators to the start and end of an array. The difference between these iterators gives the array's length.

Code
#include
#include
using namespace std;

int main() {
    int arr[] = {11, 22, 33, 44};
    cout << "The length of the array is: " << end(arr) - begin(arr);
    return 0;
}

Output:

Code
The length of the array is: 4

This method directly calculates the difference between the iterators, providing an elegant solution.

3. Using the sizeof() Function

The sizeof() operator calculates the size of the array in bytes. Dividing this value by the size of one element gives the total number of elements in the array.

Code
#include
using namespace std;

int main() {
    int arr[] = {10, 20, 30};
    int length = sizeof(arr) / sizeof(arr[0]);
    cout << "The length of the array is: " << length;
    return 0;
}

Output:

Code
The length of the array is: 3

This method is both simple and efficient, making it a common choice among developers.

4. Using the size() Method from STL

When using std::array from the Standard Template Library (STL), the size() method directly returns the number of elements.

Code
#include
#include
using namespace std;

int main() {
    array<int, 5> arr = {1, 2, 3, 4, 5};
    cout << "The length of the array is: " << arr.size();
    return 0;
}

Output:

Code
The length of the array is: 5

This method is recommended for modern C++ development when working with std::array.

5. Using Pointers

Pointers can also be used to calculate the length of an array. The expression *(&arr + 1) gives the address immediately after the array’s last element. Subtracting the array’s base address (arr) yields the length.

Code
#include
using namespace std;

int main() {
    int arr[] = {5, 4, 3, 2, 1, 0};
    int length = *(&arr + 1) - arr;
    cout << "The length of the array is: " << length;
    return 0;
}

Output:

Code
The length of the array is: 6

This approach leverages pointer arithmetic and is a useful alternative.

Conclusion

Each method described above provides a valid way to calculate the length of an array in C++. The choice of method depends on the specific requirements and context of your program. Among these, the for-each loop stands out for its simplicity and reliability across platforms.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren