Array Basics in C++
What is an Array?
An array in C++ is a fundamental data structure that stores multiple elements of the same type in contiguous memory locations. It provides a way to organize and access multiple values efficiently under a single variable name.
Declaring Arrays
In C++, you can declare an array using the following syntax:
dataType arrayName[arraySize];
Examples of Array Declarations
// Integer array with 5 elements
int numbers[5];
// Character array with 10 elements
char letters[10];
// Double array with 3 elements
double prices[3];
Initializing Arrays
There are multiple ways to initialize arrays in C++:
Method 1: Direct Initialization
int scores[4] = {85, 90, 75, 88};
Method 2: Partial Initialization
int ages[5] = {20, 25, 30}; // Remaining elements are set to 0
Method 3: Automatic Size Determination
int days[] = {1, 2, 3, 4, 5}; // Size automatically determined
Accessing Array Elements
Array elements are accessed using their index, which starts from 0:
int fruits[3] = {10, 20, 30};
int firstFruit = fruits[0]; // Value is 10
int secondFruit = fruits[1]; // Value is 20
Key Characteristics of Arrays
Characteristic |
Description |
Fixed Size |
Arrays have a static size determined at compile time |
Zero-Indexing |
First element is at index 0 |
Contiguous Memory |
Elements are stored in adjacent memory locations |
Type Consistency |
All elements must be of the same data type |
Memory Representation
graph LR
A[Array Memory Layout]
A --> B[Index 0]
A --> C[Index 1]
A --> D[Index 2]
A --> E[Index n-1]
Common Pitfalls
- No automatic bounds checking
- Risk of buffer overflow
- Fixed size limitation
Best Practices
- Always initialize arrays before use
- Check array bounds to prevent errors
- Consider using
std::array
or std::vector
for more safety
Example Program
#include <iostream>
int main() {
int temperatures[5] = {72, 68, 75, 80, 69};
for (int i = 0; i < 5; ++i) {
std::cout << "Temperature " << i+1 << ": "
<< temperatures[i] << "ยฐF" << std::endl;
}
return 0;
}
By understanding these array basics, you're ready to explore more advanced array techniques in LabEx's C++ programming environment.