C++ Arrays Introduction
What are Arrays?
Arrays are fundamental data structures in C++ that store multiple values of the same type in contiguous memory locations.
Key characteristics:
- Fixed size for built-in (C-style) arrays; the size is part of the type and known at compile time (it can be specified explicitly or deduced from the initializer).
- Elements are laid out sequentially in memory.
- All elements share the same type.
- Access to elements is constant time (O(1)).
Array Declaration Syntax
data_type array_name[array_size];
Memory Layout
Arrays occupy contiguous memory blocks. For example, consider:
int arr[3] = {10, 20, 30};
Memory Address | Value
----------------|------
0x1000 | 10 (arr[0])
0x1004 | 20 (arr[1])
0x1008 | 30 (arr[2])
(Addresses shown assuming a 4-byte int; actual sizes and addresses are implementation-defined.)
Initialization Techniques
Arrays can be initialized in different ways:
// Fully initialized
int primes[5] = {2, 3, 5, 7, 11};
// Partial initialization (remaining elements value-initialized to 0)
int scores[10] = {95, 87};
// Size deduced by compiler
char vowels[] = {'a', 'e', 'i', 'o', 'u'};
// Uniform initialization (C++11 and later) — avoid narrowing
float temps[3] {98.6f, 99.2f, 100.1f};
// Zero-initialize all elements (C++11+)
int zeros[4]{}; // {0,0,0,0}