Learn how to determine an array's length in C++ using sizeof, std::size, and template helpers. Clear examples, common pitfalls, and best practices for safe array sizing.
The length (or size) of an array means:
How many elements are stored in the array
Example:
int marks[5] = {60, 70, 80, 90, 100};
➡ The length of this array is 5 because it has 5 values.
sizeof (Most Common in C++)array_length = sizeof(array) / sizeof(array[0]);
sizeof(array) → total memory used by the arraysizeof(array[0]) → memory used by one element#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int length = sizeof(numbers) / sizeof(numbers[0]);
cout << "Length of array: " << length;
return 0;
}
Length of array: 5
#include <iostream>
using namespace std;
int main() {
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
int length = sizeof(vowels) / sizeof(vowels[0]);
cout << "Number of vowels: " << length;
return 0;
}
Number of vowels: 5
strlen() (for strings only)#include <iostream>
#include <cstring>
using namespace std;
int main() {
char name[] = "Yasir";
cout << "Length of name: " << strlen(name);
return 0;
}
Length of name: 5
🔹 strlen() counts characters excluding the '\0' (null character).
#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 4, 6, 8, 10};
int count = 0;
for(int i = 0; i < 5; i++) {
count++;
}
cout << "Array length: " << count;
return 0;
}
⚠️ This works only when you already know the size.
❌ You cannot find the length of an array using sizeof inside a function when passed as a parameter.
Example (Wrong):
void show(int arr[]) {
cout << sizeof(arr); // gives size of pointer, not array
}
✔ Correct way: pass the size separately.
| Method | Used For | Beginner Friendly |
|---|---|---|
sizeof(array)/sizeof(array[0]) |
Any array | ✅ Best |
strlen() |
Strings only | ✅ |
| Loop counting | Practice only | ⚠️ |