Getting the Size of an Array in C++

You can determine the number of elements in an array using the sizeof operator. This is useful when the array size is not explicitly known.

Example: Calculating Array Size

int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
std::cout << "Array Size: " << size << std::endl;

Key Takeaways

  • sizeof(array) returns the total memory size of the array.
  • sizeof(array[0]) gives the size of one element.
  • Divide the total size by the element size to get the number of elements.