Day#90 C' Coding Challenge

Day#90 C' Coding Challenge

Can we have negative index for arrays in C programming language?

----------------------------------

The array is declared as below:

int a[10];

There are two scenarios where,

1. Base address of array is zero
2. Base address of array is non-zero

When the base address is zero and when try to access a[-1] which meant Base address-1. This leads to a negative address and gives an illegal address access error.

When the base address is non-zero and at least, size of int in this case, then a[-1] is valid.

----------------------

For example, with the below program, negative index is allowed:

#include<stdio.h>

#define FALSE 0

int main()
{
int arr[10]= {1,2,3};
printf("%d\n",arr);
printf("%d\n",&arr[-1]);
printf("%d",arr[-1]);
return FALSE;

The above code returns below output and negative index is a valid address in this case.

6487536
6487532
0
---------------------------

Post a Comment

0 Comments