Open In App

Is it valid to address an element beyond the end of an Array?

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The array is the collection of the same type of data- type. To know more about arrays, refer here.

What happens when we address an element beyond end of Array?

When we address any element beyond the end of the array, we generally face an error (Array out of bound Index). This makes the code stop working and we have to set edge conditions in order to tackle it.

Some Language-specific Cases:

C / C++ language:

In the case of C/C++, if you read or write beyond allocated memory, then the C/C++ standard says it’s undefined behavior. In C++/C if you try to access an element that is beyond the allocated memory, it will give you zero(0) or garbage value in some cases.

Below is the code to implement in C/C++:

C++
// C++ code to illustrate the case
#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };

    // Beyond the array
    cout << arr[5] << endl;

    // Within the array
    cout << arr[4] << endl;
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Define an array with elements 1, 2, 3, 4, 5
        int[] arr = { 1, 2, 3, 4, 5 };

        // Accessing an index beyond the array bounds
        try {
            // Trying to access index 5, which is beyond the array bounds
            System.out.println(arr[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            // Catching the exception thrown for accessing beyond the array bounds
            System.out.println("Accessing beyond the array bounds.");
        }

        // Accessing within the array bounds
        System.out.println(arr[4]); // Accessing index 4, which is within the array bounds
    }
}
C#
using System;

class Program
{
    static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5 };

        // Beyond the array
        Console.WriteLine(arr[5]);

        // Within the array
        Console.WriteLine(arr[4]);

    }
}
Javascript
// JavaScript does not have fixed-size arrays like C++, so we'll use regular JavaScript arrays.

// Main function
function main() {
    // Initialize an array with elements
    let arr = [1, 2, 3, 4, 5];

    // Beyond the array
    console.log(arr[5]); // This will result in undefined because there is no element at index 5 in the array

    // Within the array
    console.log(arr[4]); // This will print the value 5, as it's within the array bounds
}

// Call the main function
main();
Python3
# Python code to illustrate the case

# Define the array
arr = [1, 2, 3, 4, 5]

try:
    # Beyond the array
    #Note in Python accessing the index beyond the arr raises an index error
    print(arr[5])

    # Within the array
    print(arr[4])

except IndexError as e:
    # Handle index out of bounds error
    print("Index out of bounds:", e)

Output
32767
5

Java/C# language:

In case of Java and C# language, the compiler throws an exception “ArrayOutOfBoundsException”. Here’s an example of the error:

C++
#include <iostream>

int main() {
    int arr[] = { 1, 2, 3, 4, 5 };
    // Accessing Beyond the array
    std::cout << arr[5] << std::endl;
    return 0;
}
Java
// JAVA implementation
public class GFG {
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5 };

        // Accessing Beyond the array
        System.out.println(arr[5]);
    }
}
C#
// C# implementation
using System;

public class GFG {
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        // Accessing Beyond the array
        Console.WriteLine(arr[5]);
    }
}
JavaScript
// JavaScript implementation
let arr = [1, 2, 3, 4, 5];

// Accessing Beyond the array
console.log(arr[5]);
Python3
# Python code to illustrate the case

if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]

    # Beyond the array
    print(arr[5])

# This code is contributed by rishab

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at GFG.main(GFG.java:6)

Python Language:

As you can see, attempting to access an element beyond the end of the list will raise an “IndexError” exception in Python, just like in C++. It’s important to handle the index properly and make sure it is within the bounds of the list before accessing its elements.

Python3
numbers = [1, 2, 3, 4, 5]

# Beyond the array, will raise IndexError
print(numbers[5]) # IndexError: list index out of range

# Within the array
print(numbers[4]) # 5
The error message you're seeing, "IndexError: list index out of range", indicates that you're trying to access an 
element of a list that is beyond the end of the list. In Python, lists are zero-indexed, meaning the first element
is at index 0, the second element is at index 1, and so on. The highest valid index in the numbers list is 4, since
the list has 5 elements, and the last element is located at index 4. Attempting to access an element at index 5,
which is beyond the end of the list, will raise an "IndexError: list index out of range" exception.

Javascript:

Javascript
let myArray = [1, 2, 3, 4, 5];

// Check if the index is within bounds before accessing the element
function getElementAtIndex(index) {
    if (index >= 0 && index < myArray.length) {
        return myArray[index];
    } else {
        console.log("Index out of bounds");
        return null; // or handle the error in a way that makes sense for your application
    }
}

// Example usage
console.log(getElementAtIndex(2));  // Output: 3
console.log(getElementAtIndex(10)); // Output: Index out of bounds

Output
3
Index out of bounds
null

Related Articles:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads