Complete Guide to C++ Arrays
- Sharpen your programming skills by learning how to create, assess, and modify arrays and strings in C.
- Beginner Friendly.2 hours2 hours
- Learn how to organize data and automate repetitive tasks with arrays and loops.
- Beginner Friendly.3 hours3 hours
What are C++ arrays?
In C++, an array is a variable that can store multiple values of the same type. C++ arrays are fundamental data structures that allow you to organize related information in contiguous memory locations.
For example, suppose you need to store test scores for 30 students. Instead of creating 30 separate variables, you can create a single array :
int testScores[30];Copy to clipboardCopy to clipboard
Here, testScores is an array that can hold 30 integer values representing student scores.
Key characteristics
C++ arrays have several important features:
Fixed size: The size cannot be changed after declaration
Same data type: All elements must be of the same type
Zero-based indexing: First element is at index 0
Contiguous memory: Elements are stored next to each other in memory
No bounds checking: You must manually ensure valid array access
Arrays vs vectors
If youโve used C++ vectors before, you might wonder when to use arrays in C++ versus vectors.
| Feature | Arrays | Vectors |
|---|---|---|
| Size | Fixed at compile time | Can grow/shrink dynamically |
| Performance | Faster (no overhead) | Slightly slower |
| Safety | No bounds checking | Built-in bounds checking |
| Memory | Stack allocation | Heap allocation |
Use arrays when:
You know the exact size needed
Maximum performance is critical
Working with embedded systems
Use vectors when:
Size may change during runtime
You need safety features
Rapid development is a priority
Array declaration
The syntax for declaring arrays is:
dataType arrayName[arraySize];Copy to clipboardCopy to clipboard
Example:
int numbers[5];// Array of 5 integersdouble prices[10];// Array of 10 doubleschar letters[26];// Array of 26 charactersCopy to clipboardCopy to clipboard
Important: Array size must be a compile-time constant and cannot use variables.
Array initialization
You can initialize arrays in several ways:
// Method 1: Specify all valuesint numbers[5]={10,20,30,40,50};// Method 2: Let compiler determine sizeint autoSize[]={1,2,3,4,5};// Size automatically becomes 5// Method 3: Partial initialization (rest become 0)int partial[5]={1,2};// First two are 1,2; rest are 0// Method 4: Initialize all to zeroint zeros[5]={};// All elements become 0// Character arrayschar vowels[5]={'a','e','i','o','u'};char word[]="Hello";// Automatically sized for stringCopy to clipboardCopy to clipboard
Accessing array elements
Use square brackets with the index to access elements. Arrays use zero-based indexing.
int scores[5]={85,90,78,92,88};// Access elementsint first = scores[0];// 85 (first element)int third = scores[2];// 78 (third element)int last = scores[4];// 88 (last element)Copy to clipboardCopy to clipboard
Elements are stored consecutively in memory with addresses increasing by the size of the data type.
Modifying array elements
You can change array elements after creation:
int grades[5]={75,80,85,90,95};// Update individual elementsgrades[0]=80;// Change first elementgrades[2]= grades[2]+5;// Add 5 to third element// Result: {80, 80, 90, 90, 95}Copy to clipboardCopy to clipboard
Array traversal
Example 1: Display array elements using a for loop
#include<iostream>usingnamespace std;intmain(){int numbers[5]={10,20,30,40,50};cout <<"Array elements: ";for(int i =0; i <5; i++){cout << numbers[i]<<" ";}cout << endl;return0;}Copy to clipboardCopy to clipboard
Output:
Array elements: 10 20 30 40 50Copy to clipboardCopy to clipboard
In this program, we have declared an array numbers with 5 elements. We use a for loop to iterate through the array from index 0 to 4. In each iteration, we print the element at the current index using numbers[i]. The loop variable i serves as the array index, allowing us to access each element sequentially.
Example 2: Take input and store in an array
#include<iostream>usingnamespace std;intmain(){int numbers[5];cout <<"Enter 5 numbers: "<< endl;// Store input from user to arrayfor(int i =0; i <5; i++){cin >> numbers[i];}cout <<"You entered: ";// Print array elementsfor(int i =0; i <5; i++){cout << numbers[i]<<" ";}cout << endl;return0;}Copy to clipboardCopy to clipboard
Output:
Enter 5 numbers:1123445678You entered: 11 23 44 56 78Copy to clipboardCopy to clipboard
Explanation:
Here, we first declare an array numbers without initializing it. We then use a for loop to take input from the user and store it in the array using cin >> numbers[i]. After storing all inputs, we use another for loop to display the array elements. This demonstrates how arrays can store user input dynamically during program execution.
Finding array size
Arrays donโt have a built-in size method. Use the sizeof operator:
int arr[10]={1,2,3,4,5,6,7,8,9,10};int size =sizeof(arr)/sizeof(arr[0]);cout <<"Array size: "<< size << endl;// Output: 10Copy to clipboardCopy to clipboard
Important: This only works in the same scope where the array is declared. When passing arrays to functions, you must pass the size as a separate parameter.
Passing arrays to functions
Arrays are always passed as pointers to functions. You must pass the size separately since arrays lose size information when passed.
voidprintArray(int arr[],int size){for(int i =0; i < size; i++){cout << arr[i]<<" ";}cout << endl;}intmain(){int numbers[5]={1,2,3,4,5};printArray(numbers,5);// Pass array and sizereturn0;}Copy to clipboardCopy to clipboard
Use const for read-only arrays to prevent accidental modification:
voiddisplayArray(constint arr[],int size){// Function cannot modify arr elementsfor(int i =0; i < size; i++){cout << arr[i]<<" ";}}Copy to clipboardCopy to clipboard
Multidimensional arrays
Arrays can have multiple dimensions for matrices, tables, and grids.
Example 3: Working with two-dimensional arrays
#include<iostream>usingnamespace std;intmain(){// 3x4 matrix (3 rows, 4 columns)int matrix[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};// Access specific elementcout <<"Element at [1][2]: "<< matrix[1][2]<< endl;// Print entire matrixcout <<"Complete matrix:"<< endl;for(int row =0; row <3; row++){for(int col =0; col <4; col++){cout << matrix[row][col]<<"\t";}cout << endl;}return0;}Copy to clipboardCopy to clipboard
Output:
Element at [1][2]: 7Complete matrix:1 2 3 45 6 7 89 10 11 12Copy to clipboardCopy to clipboard
In this example, we create a 2D array matrix with 3 rows and 4 columns. The array is initialized with values arranged in a grid format. We first access and print a specific element at position [1][2], which gives us 7 (second row, third column). Then we use nested for loops to traverse and print the entire matrix. The outer loop iterates through rows, while the inner loop iterates through columns, printing each element followed by a tab space for proper formatting.
When passing 2D arrays to functions, you must specify all dimensions except the first:
voidprocessMatrix(int matrix[][4],int rows){for(int i =0; i < rows; i++){for(int j =0; j <4; j++){matrix[i][j]*=2;}}}Copy to clipboardCopy to clipboard
Common array operations
Here are some essential operations youโll frequently perform with arrays in your C++ programs.
Finding maximum and minimum
intfindMax(constint arr[],int size){int max = arr[0];for(int i =1; i < size; i++){if(arr[i]> max){max = arr[i];}}return max;}intfindMin(constint arr[],int size){int min = arr[0];for(int i =1; i < size; i++){if(arr[i]< min){min = arr[i];}}return min;}Copy to clipboardCopy to clipboard
Output:
Array elements: 45 23 67 12 89 34Maximum value: 89Minimum value: 12Copy to clipboardCopy to clipboard
The findMax function iterates through the array, comparing each element with the current maximum value. Similarly, findMin finds the smallest value by comparing elements. Both functions start with the first element as the initial value and then compare with remaining elements.
Calculating sum and average
#include<iostream>usingnamespace std;intcalculateSum(constint arr[],int size){int sum =0;for(int i =0; i < size; i++){sum += arr[i];}return sum;}doublecalculateAverage(constint arr[],int size){returnstatic_cast<double>(calculateSum(arr, size))/ size;}intmain(){int scores[5]={85,92,78,96,88};cout <<"Test scores: ";for(int i =0; i <5; i++){cout << scores[i]<<" ";}cout << endl;int total =calculateSum(scores,5);double avg =calculateAverage(scores,5);cout <<"Total sum: "<< total << endl;cout <<"Average score: "<< avg << endl;return0;}Copy to clipboardCopy to clipboard
Output:
Test scores: 85 92 78 96 88Total sum: 439Average score: 87.8Copy to clipboardCopy to clipboard
The calculateSum function adds all array elements together using a loop. The calculateAverage function uses the sum and divides it by the array size. We use static_cast<double> to ensure floating-point division for accurate average calculation.
Searching for elements
intlinearSearch(constint arr[],int size,int target){for(int i =0; i < size; i++){if(arr[i]== target){return i;// Return index if found}}return-1;// Return -1 if not found}Copy to clipboardCopy to clipboard
Output:
Array elements: 10 25 30 45 60 75 80Element 45 found at index 3Copy to clipboardCopy to clipboard
The linearSearch function examines each array element sequentially until it finds the target value or reaches the end. It returns the index position if the element is found, or -1 if not found. This is useful for locating specific values in unsorted arrays.
Array limitations and safety
Arrays have several limitations that require careful programming:
No bounds checking: Accessing invalid indices causes undefined behavior
Fixed size: Cannot resize after declaration
Size information lost: Arrays decay to pointers in functions
Buffer overflow risk: Writing beyond bounds can corrupt memory
Best practices for using C++ arrays
Following these guidelines will help you write safer and more efficient code when working with arrays.
Always initialize arrays to avoid undefined behavior
Validate array bounds before accessing elements
Pass array size as a separate parameter to functions
Use const for read-only array parameters
Consider std::array or std::vector for additional safety features
Conclusion
C++ arrays are fundamental data structures that provide efficient storage for multiple values of the same type. Understanding arrays is essential for system-level programming, performance-critical applications, and working with legacy C code.
Frequently asked questions
1. What is the difference between arrays and vectors in C++?
Arrays have a fixed size determined at compile time and offer maximum performance with minimal overhead. Vectors are dynamic, can grow or shrink during runtime, and provide built-in safety features like bounds checking. Use arrays when size is known and performance is critical; use vectors when you need flexibility and safety.
2. How do you find the size of an array in C++?
Use the sizeof operator: int size = sizeof(array) / sizeof(array[0]);. This only works in the same scope where the array is declared. When arrays are passed to functions, you must pass the size as a separate parameter since arrays decay to pointers.
3. Can you change the size of an array after declaration?
No, C++ arrays have a fixed size that cannot be changed after declaration. If you need dynamic sizing, use std::vector or dynamically allocate memory using new and delete.
4. What happens if you access an array element outside its bounds?
Accessing an array element outside its bounds results in undefined behavior. This can lead to program crashes, data corruption, or security vulnerabilities. Always validate array indices before accessing elements.
5. How are multidimensional arrays stored in memory?
Multidimensional arrays are stored in row-major order in contiguous memory locations. For a 2D array arr[3][4], elements are stored as: arr[0][0], arr[0][1], arr[0][2], arr[0][3], arr[1][0], and so on.
6. Why do arrays decay to pointers when passed to functions?
This behavior is inherited from C for efficiency. Instead of copying the entire array, only the address of the first element is passed. This saves memory and time but loses size information, which is why you need to pass the size separately.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
What is a for Loop in C++?
Learn how to use a `for` loop in C++ with syntax, examples, and use cases. Understand nested and range-based `for` loops and their real-world applications. - Article
Creating and Using NumPy Arrays - A Complete Guide
Learn how to create NumPy arrays with `np.array()` in Python. Complete guide covering 1D, 2D, 3D arrays, indexing, slicing, and manipulation techniques. - Article
C++ Pointers Explained: Types, Examples & Best Practices
Learn how to use C++ pointers in this complete guide. Understand types, syntax, advantages, disadvantages, and best practices for safe memory management.
Learn more on Codecademy
- Sharpen your programming skills by learning how to create, assess, and modify arrays and strings in C.
- Beginner Friendly.2 hours2 hours
- Learn how to organize data and automate repetitive tasks with arrays and loops.
- Beginner Friendly.3 hours3 hours
- Create and manipulate arrays and execute efficient repetitions using loops to develop meaningful programs.
- Beginner Friendly.3 hours3 hours
- What are C++ arrays?
- Arrays vs vectors
- Array declaration
- Array initialization
- Accessing array elements
- Modifying array elements
- Array traversal
- Finding array size
- Passing arrays to functions
- Multidimensional arrays
- Common array operations
- Array limitations and safety
- Best practices for using C++ arrays
- Conclusion
- Frequently asked questions
