Szerkesztő:LinguisticMystic/cpp/Arrays
🔢 Arrays in C++
[szerkesztés]Arrays are a fundamental and powerful data structure in C++. They allow programmers to efficiently store, manage, and access multiple values using a single variable name. Arrays are especially useful when dealing with collections of data that are logically related and share the same type.
📌 Key Features of Arrays in C++
[szerkesztés]
✅ Contiguous Memory
[szerkesztés]Arrays store elements in contiguous (adjacent) memory locations. This arrangement allows the compiler to calculate the address of any element using a simple formula:
address_of_element = base_address + (index * size_of_element)
As a result, arrays support fast, constant-time access (O(1)) to any element, which is a big performance advantage.
✅ Fixed Size
[szerkesztés]An array’s size is fixed once declared. This means:
int numbers[10]; // Can hold exactly 10 integers
You cannot resize the array later without reallocating a new array. This makes arrays static in size, unlike dynamic containers like std::vector.
✅ Zero-Based Indexing
[szerkesztés]Array indices start from 0, not 1. For an array of size n, valid indices range from 0 to n - 1.
int arr[3] = {10, 20, 30};
std::cout << arr[0]; // 10
std::cout << arr[2]; // 30
Accessing an invalid index like arr[3] results in undefined behavior.
✅ Homogeneous Elements
[szerkesztés]All elements in an array must be of the same data type. This ensures:
- Uniform memory allocation
- Consistent behavior
- Efficient indexing
✅ Random Access
[szerkesztés]You can directly access any array element using its index without traversing the array.
std::cout << numbers[4]; // instant access to 5th element
✅ Size Determination
[szerkesztés]The sizeof() operator allows determining:
- Total size of the array in bytes
- Length (number of elements), by dividing total size by the size of a single element.
int len = sizeof(arr) / sizeof(arr[0]);
✅ Array Type
[szerkesztés]Arrays can hold any valid C++ type, including:
- Built-in types (
int,char,float) - User-defined types (
struct,class) - Pointers
🏗️ Declaring and Initializing Arrays
[szerkesztés]
General Syntax:
[szerkesztés]dataType arrayName[arraySize] = {element1, element2, ..., elementN};
Components:
[szerkesztés]dataType: The type of elements (int,char, etc.)arrayName: The identifier for the arrayarraySize: The fixed number of elements it can hold{}: Optional list of initial values
🧪 Examples:
[szerkesztés]int numbers[5] = {1, 2, 3, 4, 5}; // 5 integers
float grades[3] = {98.5, 85.0, 76.25}; // 3 floats
char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; // 5 characters
Omitting Size on Initialization:
[szerkesztés]int numbers[] = {1, 2, 3, 4, 5}; // Size automatically deduced to 5
Manual Assignment After Declaration:
[szerkesztés]int numbers[5];
numbers[0] = 654;
numbers[3] = 9;
Uninitialized Arrays:
[szerkesztés]If not explicitly initialized, arrays of primitive types contain garbage values:
int numbers[5];
std::cout << numbers[0]; // undefined value
🧾 Accessing Array Elements
[szerkesztés]
Example:
[szerkesztés]char vowels[5] = {'H', 'e', 'l', 'l', 'o'};
std::cout << vowels[0] << vowels[1] << vowels[2]; // Output: Hel
Caution:
[szerkesztés]Accessing outside the bounds:
int arr[5] = {1, 2, 3, 4, 5};
std::cout << arr[5]; // ❌ Undefined behavior
C++ does not automatically check bounds. Use caution or consider std::array or std::vector with .at() for safety.
🔗 Arrays and Pointers
[szerkesztés]In C++, arrays and pointers are closely related.
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers; // same as &numbers[0]
You can use pointer arithmetic to navigate:
std::cout << *ptr; // numbers[0]
std::cout << *(ptr + 1); // numbers[1]
Also, when you pass an array to a function, what actually gets passed is a pointer to its first element — not the entire array.
🔢 Multi-Dimensional Arrays
[szerkesztés]Useful for representing matrices, grids, tables, etc.
int matrix[3][4]; // 3 rows, 4 columns
Initialization:
[szerkesztés]int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Access:
[szerkesztés]std::cout << matrix[0][0]; // 1
std::cout << matrix[2][3]; // 12
Note: C++ also supports arrays with more than two dimensions (int cube[2][3][4];), though they become harder to manage.
📏 Determining Length and Size
[szerkesztés]
Example:
[szerkesztés]int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr); // Total size in bytes (e.g., 20 if int = 4 bytes)
int length = sizeof(arr) / sizeof(arr[0]); // Number of elements (5)
std::cout << size << ", " << length;
📌 Summary
[szerkesztés]| Feature | Description |
|---|---|
| Contiguous | Stored in consecutive memory |
| Fixed-size | Size set at declaration |
| Zero-indexed | Indexing starts from 0 |
| Homogeneous | All elements have same type |
| Random access | Instant access via index |
| No bounds checking | Unsafe if accessed out-of-bounds |
| Pointer compatible | Arrays decay into pointers |
🧠 Conclusion
[szerkesztés]Arrays are one of the most basic but powerful tools in C++. By learning how to declare, initialize, and manipulate them, you unlock the ability to manage data collections efficiently. However, due to lack of bounds checking and fixed size, always ensure safe indexing and consider alternatives like std::vector for dynamic use cases.
🛡️ Tip: For modern and safer code, use
std::arrayorstd::vectorfrom the STL whenever dynamic size or bounds-checking is needed.