C++ Get Array Size

In C++, you can determine the size of an array using the sizeof() operator, which returns the memory size in bytes.

Tutorials dojo strip

Using sizeof() to Get Array Size

The sizeof() operator calculates the total storage size of an array.

Example: Checking Array Size in Bytes

C++

Output:

C++

Even though the array contains 5 elements, the output shows 20 because:

  • The sizeof() operator returns the size in bytes.
  • An int is typically 4 bytes.
  • The total storage = 4 bytes × 5 elements = 20 bytes.

Calculating the Number of Elements in an Array

To determine the actual number of elements, divide the total array size by the size of one element.

Example: Getting the Array Length

C++

Output:

C++

This ensures an accurate element count, regardless of data type.

Looping Through an Array Using sizeof()

Instead of hardcoding the array size in a loop, use sizeof() to make loops adaptable to any array length.

Example: Iterating Over an Array

C++

This approach ensures the loop works for any array size without manual updates.

Using For-Each Loop (C++ version 11)

A more concise way to loop through arrays is with the range-based for loop.

Example

C++

This method automatically handles each element, eliminating manual index tracking.

Tutorials dojo strip