Negative array index in C++

Hi guys, today we will discuss how to declare an array, how to enter the values in an array, and how to access the negative array index in C++.

Before moving to the negative index, let us discuss something about arrays.

Now, let us see how to define an array.

The syntax of array declaration is:

data_type variable_name [size];
Example- int arr[5];

So, in this case, the data type is integer, the name of the array is ‘arr’ and its size is 5.

The integer uses 4 bytes in the memory.

Now, let us see how to enter the elements in an array:

int arr[5];
for(int i=0;i<5;i++)

From this code, we can take 5 integers as input.

Now, let us see how to print the elements of an array:

for(int i=0;i<5;i++)
       cout<<arr[i]<<" ";

By using this method, all the elements of the array will be printed in a line separated by a space.

Negative Array Index

Most of you must have tried to access the negative index of an array and can do it.

You are must be having a question that why am I able to access the negative index?

Before moving to the answer, let us see an example

using namespace std;
int main()
    int arr[5];
    for(int i=-5;i<5;i++)
    for(int i=-5;i<5;i++)
        cout<<arr[i]<<" ";
        return 0;

In this code, I have declared an integer array of size 5.
In this first loop, I have initialized all the elements of the array will its index+10.
And, in the second loop, I have printed them.

In this code, I have accessed the negative array.

So, why it is possible to access more than 5 elements in this array?

The answer is that when I declare the array ‘arr’ of size 5, 20 bytes is allocated to it in the memory.

Let us assume that the starting address of the memory assigned to ‘arr’ is 700. So, when we try to print arr[1], it will move 4 bytes ahead and print the value at address 704.

Similarly, when we try to print arr[-1], it will move 4 bytes behind 700 and print the value present at the address 696.

But, now you will ask why it is able to access 696 when its memory is from 700 to 719?
So, the thing is that free memory is assigned to a new variable that means the memory in our system is free from address 700 and something is stored before 700.
That means when we try to access the address 696 in the memory, whatever is stored at that address gets overwrite by the new value. And hence, when we try to print its value, it returns the updated value.

The output for the above code will be:

5 6 7 8 9 10 11 12 13 14

You can practice more questions based on the array to get a better hold on the topic. Here are some links that you can refer to:

Leave a Reply

Your email address will not be published. Required fields are marked *