← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 4 of 15

C++ Array Size

An array's size is fixed at declaration, and sizeof combined with dividing by one element's size is the standard C++ way to compute how many elements it holds, though std::vector avoids this entirely.

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

cpp
#include <iostream>

int main() {
	int arr[5] = {1, 2, 3, 4, 5};
	std::cout << "Fixed size: 5" << std::endl;
	return 0;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#include <iostream>

int main() {
	int arr[] = {1, 2, 3, 4, 5};
	std::cout << std::size(arr) << std::endl;
	return 0;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.