Core Module
12 min forge

C++ Arrays

Fixed-size collections of elements of the same type stored in contiguous memory.

C++ Arrays

πŸ“˜ What is it

An array is a collection of elements of the same type stored in contiguous memory locations. In C++, array size must be known at compile-time for static arrays.

⚑ When to use

Use static arrays when the number of elements is fixed and known beforehand to save memory overhead compared to dynamic containers.

🧠 Time complexity

  • Access by index: $O(1)$
  • Search (unsorted): $O(N)$
  • Insertion/Deletion: $O(N)$ (requires shifting elements)

πŸ’» Code example

cpp Standard
int arr[5] = {10, 20, 30, 40, 50}; int x = arr[2]; // Accessing 30

❌ Common mistakes

  • Array bounds overflow: Accessing arr[5] for an array of size 5 (indices are 0 to 4).
  • Forgetting that arrays cannot be resized once declared.
  • Not initializing array elements, leading to garbage values.