Click to See Complete Forum and Search --> : Why negative subscript in array?
Knight_G
October 28th, 2001, 12:31 AM
Can somebody pls explain to me why there can be negative subscript in the array
eg, a[-1] = 1;
this has no error!!! i can even put any negative subscript there. why?
thanks
hariprasadv
October 28th, 2001, 01:32 AM
hi
Actually a[0] == (a+0)==(base Address + relative Address)
When ever we declare an array it is provided only the base address and the size,
if we use a[-1] is nothing but assigning/accessing the value which is pointing previous location of the base address pointer,
this will give problem only when a[-1] refers to code segemnt,
Knight_G
October 28th, 2001, 03:14 AM
do you mean that using negative subscript will produce error when there are more statements?
Nikolai Borissov
October 28th, 2001, 12:27 PM
When you declare array like this:
elem_type arr[const_expr];
memory will be allocated only for 0,1,...,(const_expr-1) elements of the array. Internally array is treated as a pointer to element type and, therefore, you CAN address beyond allocated area using indices i<0 or i>=const_expr. This is called array boundary violation. Generally, at compile time it's not possible to catch these violations. However, there is a compiler option that will cause compiler to generate a boundary-checking code so that the check will occur at run time (at the expence of performance of course).
What happens when you violate array boundaries? Nothing good. You may corrupt other variables and/or system data. As a result - weird and difficult to recover run-time errors.
Nikolai
Paul McKenzie
October 28th, 2001, 04:01 PM
This code uses negative subscripts and is not an error, neither at compile time or run-time.
int main()
{
char name[] = "ABC123";
char *pName = name + 3;
printf("This is the character 'C' %c" ,pName[-1]);
}
pName points to the '1' in "ABC123", so pName[-1] points to one character before the '1', which is the 'C'. This should illustrate why negative subscripts are legal in C or C++. pName[-1] points to a valid location.
Regards,
Paul McKenzie
thew
October 28th, 2001, 07:50 PM
People here have said it. But to just expand what they've alluded too.
char pArray[4] = "abc"; // "abc" resides in the static segment SS
// is the same as
char *pArray = "abc"; // "abc" resides in the data segment DS
// which means
*(pArray+1) == 'a'; // is the same as
pArray[1] == 'a'; // which is true
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.