C++ Array Size
In this page:
Fixed Size at Declaration
A C-style array's size is fixed at the moment it's declared, specified as a number inside square brackets, and unlike std::vector, it cannot grow or shrink after that.
Example: Fixed Size at Declaration
#include <iostream>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
std::cout << "Fixed size: 5" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Finding an Array's Size with sizeof
The sizeof operator applied to an array returns the total number of bytes it occupies, and dividing that by the size of a single element, using sizeof(arr[0]), is the standard way to compute how many elements it holds.
Example: Finding an Array's Size with sizeof
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int count = sizeof(arr) / sizeof(arr[0]);
std::cout << count << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Size of Arrays Passed to Functions
When an array is passed as a function parameter, it decays into a pointer, so sizeof inside that function reports the size of the pointer rather than the original array, requiring the element count to be passed in separately.
Example: Size of Arrays Passed to Functions
#include <iostream>
void checkSize(int arr[]) {
std::cout << sizeof(arr) << std::endl; // reports pointer size, not array size
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
std::cout << sizeof(arr) << std::endl; // full array size
checkSize(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
std::size() for Modern Array Sizing
C++17 introduced the free function std::size(), which returns an array's element count directly without the sizeof division trick, working on both C-style arrays and STL containers.
Example: std::size() for Modern Array Sizing
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
std::cout << std::size(arr) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
std::vector as a Sizeable Alternative
Unlike a C-style array, a std::vector tracks its own size internally and can grow or shrink at runtime, and its .size() method always returns the current element count directly.
Example: std::vector as a Sizeable Alternative
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3};
vec.push_back(4);
std::cout << vec.size() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings