In C++, you can determine the size of an array using the sizeof()
operator, which returns the memory size in bytes.
Using sizeof() to Get Array Size
The sizeof()
operator calculates the total storage size of an array.
Example: Checking Array Size in Bytes
#include <iostream> using namespace std; int main() { int engineSizes[5] = {600, 1000, 1100, 1300, 1500}; cout << sizeof(engineSizes); return 0; }
Output:
20
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
#include <iostream> using namespace std; int main() { int engineSizes[5] = {600, 1000, 1100, 1300, 1500}; int arrayLength = sizeof(engineSizes) / sizeof(engineSizes[0]); cout << arrayLength; return 0; }
Output:
5
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
#include <iostream> using namespace std; int main() { int engineSizes[] = {600, 1000, 1100, 1300, 1500}; for (int i = 0; i < sizeof(engineSizes) / sizeof(engineSizes[0]); i++) { cout << engineSizes[i] << "\n"; } return 0; }
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
#include <iostream> using namespace std; int main() { int engineSizes[] = {600, 1000, 1100, 1300, 1500}; for (int cc : engineSizes) { cout << cc << "\n"; } return 0; }
This method automatically handles each element, eliminating manual index tracking.