To find the length (number of elements) of an array in C++, the method depends on the type of array you’re working with. Below is a detailed explanation with examples for different scenarios:
1. Static Arrays (Compile-Time Known Size)
Use sizeof
to calculate the number of elements when the array is declared in the current scope.
Formula:
size_t length = sizeof(array) / sizeof(array[0]);
Example:
#include <iostream>
int main() {
int staticArray[] = {10, 20, 30, 40, 50}; // Static array
// Calculate length
size_t length = sizeof(staticArray) / sizeof(staticArray[0]);
std::cout << "Array length: " << length; // Output: 5
return 0;
}
Why this works:
sizeof(staticArray)
: Total memory size of the array (e.g.,5 ints × 4 bytes each = 20 bytes
).sizeof(staticArray[0])
: Size of one element (e.g.,4 bytes
forint
).- Result:
20 / 4 = 5
elements.
Limitations:
- Fails if the array decays to a pointer (e.g., when passed to a function).
2. Dynamic Arrays (Heap-Allocated)
For arrays created with new[]
, you must manually track the length. C++ does not provide a built-in way to get their size.
Example:
#include <iostream>
int main() {
int size = 7;
int* dynamicArray = new int[size]{1, 2, 3, 4, 5, 6, 7}; // Heap-allocated
// You MUST store the size separately!
std::cout << "Array length: " << size; // Output: 7
delete[] dynamicArray; // Deallocate memory
return 0;
}
Key Point:
- No runtime size information: Once created,
sizeof(dynamicArray)
returns the size of a pointer (e.g.,8 bytes
on 64-bit systems), not the array size.
3. Arrays Passed to Functions
Arrays decay to pointers when passed to functions, losing size information. You must pass the size explicitly.
Example:
#include <iostream>
// Function to print an array (MUST pass size explicitly)
void printArray(int arr[], size_t size) {
for (size_t i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
}
int main() {
int staticArray[] = {10, 20, 30};
size_t length = sizeof(staticArray) / sizeof(staticArray[0]);
printArray(staticArray, length); // Pass array and size
return 0;
}
4. Using std::array
(C++11 and Later)
The modern, safer alternative to static arrays. Use .size()
to get the length.
Example:
#include <iostream>
#include <array> // Include std::array
int main() {
std::array<int, 4> stdArray = {3, 1, 4, 1};
// Get length via .size()
std::cout << "Array length: " << stdArray.size(); // Output: 4
return 0;
}
5. Using std::vector
(Dynamic Array Alternative)
Use .size()
for dynamic arrays that resize automatically.
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {5, 10, 15, 20, 25};
// Get length via .size()
std::cout << "Vector length: " << vec.size(); // Output: 5
return 0;
}
Summary of Methods
Array Type | How to Get Length | Example |
---|---|---|
Static Array | sizeof(arr) / sizeof(arr[0]) | Works in local scope only |
Dynamic Array (new[] ) | Manually track size | Store size when allocating |
Function Parameter | Pass size explicitly | void func(int arr[], size_t size) |
std::array (C++11) | Use .size() member function | std::array<int,5> a; a.size(); |
std::vector | Use .size() member function | std::vector<int> v; v.size(); |
Critical Notes
- Avoid
sizeof
for pointers:
int arr[5];
int* ptr = arr;
// WRONG! sizeof(ptr) is pointer size (e.g., 8 bytes), not array size.
- Prefer C++ containers: Use
std::array
(fixed-size) orstd::vector
(dynamic) for automatic size management and bounds checking. - Why not use C-style arrays?
They are error-prone (e.g., accidental pointer decay, no bounds checks). Modern C++ alternatives are safer.