In C++, you can get the size of an array in several ways. The most common approach depends on whether you’re using a static array (i.e., an array with a fixed size).
Example:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
// Get the size of the array
int size = sizeof(arr) / sizeof(arr[0]);
cout << "The size of the array is: " << size << endl;
return 0;
}
Explanation:
- sizeof(arr) gives the total size of the array in bytes, It has 5 element and every integer element has 4 bytes so total bytes = 5*4= 20.
- sizeof(arr[0]) gives the size of a single element of the array.
- Dividing sizeof(arr) by sizeof(arr[0]) gives the total number of elements in the array.
Output:
Use Array Size in for loop
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
for(int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) {
cout << "Array element: " << arr[i] << endl;
}
return 0;
}
Explanation:
- Array Declaration: int arr[] = {10, 20, 30, 40, 50}; creates an array with 5 elements.
- Array Size: sizeof(arr) / sizeof(arr[0]) calculates the number of elements in the array instead of direct pass value 5.
- Looping: A for loop is used to iterate through the array and print each element
Output:
Array element: 20
Array element: 30
Array element: 40
Array element: 50
C++ Array Size – Questions and Answers
Q 1: How do you find the size of an array in C++?
Ans: Using sizeof(arr) / sizeof(arr[0]).
Q 2: What happens if you access an index outside array size?
Ans: It causes undefined behavior.
Q 3: Can array size be zero?
Ans: No, C++ does not allow zero-sized arrays.
Q 4: Is array size decided at runtime?
Ans: No, standard arrays require compile-time constant size.
Q 5: Which alternative supports dynamic size?
Ans: vector from STL.
C++ Array Size – Objective Questions (MCQs)
Q1. Which operator is used to find the size of an array in C++?
Q2. What does sizeof(arr) return for the following code?
int arr[5];
cout << sizeof(arr);
Q3. How can you find the total number of elements in an array?
Q4. What will be the output?
int arr[] = {1, 2, 3, 4};
cout << sizeof(arr) / sizeof(arr[0]);
Q5. If float arr[10]; is declared, and size of float is 4 bytes, what will sizeof(arr) return?