Can negative indexes, ex: [-1], be used with arrays?
Mike
2010-02-20 09:09:02 UTC
One of my programming professors gave us some code. The program takes a number and stores it's individual digits in an array. I noticed that it uses a 'while' loop which eventually uses a negative index (-1) on its last iteration. I thought that only 0 or positive numbers could be used to refer to array locations.
Why doesn't the program crash when [-1] is passed as an array index? (ex: big_num_array[-1] )
Four answers:
Ratchetr
2010-02-20 09:15:27 UTC
You didn't say what language, but C/C++ doesn't range check the index to an array.
So array[-1] will "work". The generated code will take the address of array, add -1 * sizeof(things in array) to get a new address. It will then store the value at that address.
What happens next really depends, but it's almost never good. The address may well be a valid address, but what it points to doesn't belong to array. It might belong to some other variable. Or if array was allocated on the heap, it probably points to some internal bit of data that malloc keeps to track memory. Only if you are lucky will it point to an invalid address, and the program will crash due to an access exception before it can do any more harm.
Your professor has a bug.
James
2010-02-20 19:32:02 UTC
As mentioned before it really does depend on the language you are using to access the array at location [-1]... In C++ you will be able to access this memory location and it could refer to another variable, or piece of data that is stored at that particular memory location....
In Java, due to bounds checking, the compiler will throw what is known as an out of bounds exception error. Access to memory locations outside of the array is heavily restricted and is often why C++ is regarded as the most powerful programming language.
deonejuan
2010-02-20 18:56:53 UTC
The while loop is the condition that happens before the array call. Without seeing code snippet, that is my assumption.
Uskok
2010-02-20 17:31:05 UTC
Some languages, such as python, do use negative indices to count from the end of the array.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.