Arrays

Fixed-size arrays in C++

Interview Relevant: Basic data structure

Arrays

Arrays store fixed-size sequences of elements of the same type.

Key Points

  • Fixed size, determined at compile time
  • Zero-indexed access
  • Contiguous memory allocation
  • No bounds checking (undefined behavior if exceeded)

Code Examples

C-style array declaration, initialization, and access.

cpp
1// Declaration and initialization
2int arr[5];                    // Uninitialized
3int arr2[5] = {1, 2, 3, 4, 5}; // Initialized
4int arr3[] = {1, 2, 3};        // Size deduced (3)
5int arr4[5] = {1, 2};          // Rest are 0: {1, 2, 0, 0, 0}
6int arr5[5] = {};              // All zeros
7
8// Access elements
9arr2[0] = 10;  // First element
10arr2[4] = 50;  // Last element
11
12// Array size
13int size = sizeof(arr2) / sizeof(arr2[0]);  // 5
14
15// Iterate
16for (int i = 0; i < 5; i++) {
17    cout << arr2[i] << " ";
18}
19
20// Range-based for
21for (int x : arr2) {
22    cout << x << " ";
23}
24
25// Arrays decay to pointers
26int* ptr = arr2;  // Points to first element
27cout << *(ptr + 2);  // arr2[2]

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In