C++ Accessing Array Elements

In C++, We can access array element using array name and subscript/index written inside pair of square brackets [].

For Example :

Suppose we have an integer array of length 5 whose name is age.

int age[5] = {8,5,2,3,7};
Now we can access elements of array marks using subscript followed by array name.
  • age[0] = First element of array age = 8
  • age[1] = Second element of array age = 5
  • age[2] = Third element of array age = 2
  • age[3] = Fourth element of array age = 3
  • age[4] = Last element of array age = 7
Point To Remember
Remember array indexing starts from 0. Nth element in array is at index N-1.

C++ Accessing Array Elements Sample Program

#include <iostream>
using namespace std;
 
int main(){
    int age[7] = {8,5,2,3,7,6,7};
    int i;
    // Printing array elements using loop 
    for(i = 0; i < 7; i++){
     // Accessing array elements using i as index
        cout << "Element at index " << i <<" is " << age[i];
        cout << endl;
    }
    
    return 0;
}

Output
Element at index 0 is 8
Element at index 1 is 5
Element at index 2 is 2
Element at index 3 is 3
Element at index 4 is 7
Element at index 5 is 6
Element at index 6 is 7
In above program, we initialed an array named "age" of length seven. Using a for loop, we are printing every array element from index 0 to 6.

Passing Array to a Function in C++

In C++ programming, an array can be passed to a function as an argument. We can pass an array of any dimension to a function as argument.

  • Passing an array to a function uses pass by reference, which means any change in array data inside function's body will reflect globally.
  • When an array is passed as an argument to a function, only the name of an array is passed. Name of the array represent the address of the first element of array.
    For Example :
       int arrayName[10];
       getSum(arrayName) is equivalent to getSum(&arrayName[0]);
    

Passing Single Element of an Array to Function

We can pass one element of an array to a function like passing any other basic data type variable.

C program to pass single element of an array to function
#include <iostream>
using namespace std;
 
int getSquare(int num){
    return num*num;
}
 
int main(){
   int array[5]={1, 2, 3, 4, 5};
   int counter;
   for(counter = 0; counter < 5; counter++){
       // Passing individual array elements to function
       cout << "Square of " << array[counter] << " is " << getSquare(array[counter]);
       cout << endl;
   }

   return 0;
} 

Output
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

Passing One-dimensional Array to a Function

We can pass a one dimensional array to a function by passing the base address(address of first element of an array) of the array. We can either pass the name of the array (which is equivalent to base address) or pass the address of first element of array like &array[0]. Similarly, we can pass multi dimensional array also as formal parameters.

Different ways of declaring function which takes an array as parameter
  • Function argument as a pointer
    int testFunction(int *array){
    /* Function body */
    } 
    
  • By specifying size of an array in function parameters
    int testFunction(int array[10]){
    /* Function body */
    }
    
    the formal argument int array[10] in function declaration converts to int* array. This pointer points to the base address of array.
  • By passing unbounded array in function parameters.
    int testFunction(int array[]){
    /* Function body */
    }
    

C++ Program to Pass One Dimensional Array as Parameter to a Function

#include <iostream>
using namespace std;
 
// This function takes integer pointer as argument
void printArrayOne(int *array, int size){
    int i;
    for(i=0; i<size; i++){
        cout << array[i] << " ";
    }
    cout << endl;
}
 
// This function takes sized array as argument
void printArrayTwo(int array[5], int size){
    int i;
    for(i=0; i<size; i++){
        cout << array[i] << " ";
    }
    cout << endl;
}
 
// This function takes unbounded array as argument
void printArrayThree(int array[], int size){
    int i;
    for(i=0; i<size; i++){
        cout << array[i] << " ";
    }
    cout << endl;
}
 
int main(){
   int score[5]={1, 2, 3, 4, 5};
   // Passing name of array 
   printArrayOne(score, 5);
   printArrayTwo(score, 5);
   // passing address of first array element 
   printArrayThree(&score[0], 5);
    
   return 0;
} 

Output
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Passing Multidimensional Array to a Function

Multidimensional array with dimension 2 or more can be passed in similar way as one dimensional array.

#include <iostream>
using namespace std;
 
// This function takes sized array as argument
void printArray(int array[3][3], int rows, int cols){
    int i, j;
    for(i=0; i<rows; i++){
        for(j=0; j<cols; j++){
            cout << array[i][j] << " ";
        }
        cout << endl;
    }
}
 
int main(){
   int matrix[3][3]={{1, 2, 3},{4, 5, 6},{7, 8, 9}};
   // Passing name of array 
   printArray(matrix, 3, 3);
    
   return 0;
} 

Output
1 2 3
4 5 6
7 8 9

Returning Array from a Function in C++

In C++, we can return a pointer to the base address(address of first element of array) of array from a function like any basic data type. However, C++ programming language does not allow to return whole array from a function.

We should not return base pointer of a local array declared inside a function because as soon as control returns from a function all local variables gets destroyed. If we want to return a local array then we should declare it as a static variable so that it retains it's value after function call.

Declaration of a Function Returning Integer Array
int* getScoreList();
Above function returns the base address of an integer array.

C++ Program for Returning Array from a Function

#include <iostream>
using namespace std;
 
// This function returns an array of N even numbers
int* getEvenNumbers(int N){
    // Declaration of a static local integer array
    static int evenNumberArray[100];
    int i, even = 2;
     
    for(i=0; i<N; i++){
        evenNumberArray[i] = even;
        even += 2;
    }
    // Returning base address of evenNumberArray array
    return evenNumberArray;
}
 
int main(){
   int *array, counter;
   array = getEvenNumbers(10);
   cout << "Even Numbers\n";
   for(counter=0; counter<10; counter++){
       cout << array[counter] << " ";
   }
    
   return 0;
} 
Output
2 4 6 8 10 12 14 16 18 20
Similarly, you can return multi dimentional arrays from a function.

Best Practices for Accessing Array Elements

  • Validate Array Indices : Always validate array indices before accessing elements to prevent undefined behavior.
    int numbers[3] = {1, 2, 3};
    int index = 5;
    
    // Validate array index
    if (index >= 0 && index < 3) {
        int value = numbers[index];
    } else {
        std::cout << "Invalid index\n";
    }
    

  • Prefer Range-Based For Loops : Consider using range-based for loops when iterating through array elements, as they reduce the risk of index-related errors.
    int numbers[5] = {1, 2, 3, 4, 5};
    
    // Prefer range-based for loop
    for (int num : numbers) {
        std::cout << num << " ";
    }
    

  • Be Mindful of Array Bounds : Always stay within the valid index range when accessing and updating array elements to avoid unintended consequences.
    int numbers[3] = {10, 20, 30};
    
    // Ensure index is within bounds before updating
    int index = 1;
    if (index >= 0 && index < 3) {
        numbers[index] = 25;
    } else {
        std::cout << "Invalid index\n";
    }
    

  • Leverage Pointer Arithmetic Wisely : When using pointers with arrays, exercise caution with pointer arithmetic to avoid memory-related issues.
    int numbers[5] = {1, 2, 3, 4, 5};
    int* ptr = numbers;
    
    // Be mindful of pointer arithmetic
    // Undefined behavior (points beyond the array)
    std::cout << *(ptr + 5) << " "; 
    


Conclusion

Accessing array elements is a fundamental skill in C++ programming. By understanding the syntax, techniques, and best practices, you can confidently navigate the world of arrays and harness their power for efficient data storage and manipulation.