3.19 Negative array indices
This is the same as allocating memory for a structure usingmalloc()call. In fact,newin C++ is wrapper
formalloc(), anddeleteis wrapper forfree(). Since memory block has been allocated inheap, it must be
deallocatedexplicitly, usingdelete. Classdestructorwillbeautomaticallycalledrightbeforethatmoment.
Which method is better? Allocatingon stackis very fast, and good for small, short-lived object, which will
be used only in the current function.
Allocatingon heapis slower, and better for long-lived object, which will be used across many functions.
Also, objects allocated inheapare prone to memory leakage, because they must to be freed explicitly,
but one can forget about it.
Anyway, this is matter of taste.
3.19 Negative array indices
It’s possible to address the spacebeforean array by supplying a negative index, e.g.,array[−1].
3.19.1 Addressing string from the end.
PythonPLallows to address arrays and strings from the end. For example,string[-1]returns the last
character,string[-2]returns penultimate, etc. Hard to believe, but this is also possible in C/C++:
#include <string.h>
#include <stdio.h>
int main()
{
char s="Hello, world!";
char s_end=s+strlen(s);
printf ("last character: %c\n", s_end[-1]);
printf ("penultimate character: %c\n", s_end[-2]);
};
It works, buts_endmust always has an address of terminating zero byte at the end ofsstring. Ifsstring’s
size get changed,s_endmust be updated.
The trick is dubious, but again, this is a demonstration of negative indices.
3.19.2 Addressing some kind of block from the end.
Let’s first recall why stack grows backwards (1.7.1 on page 30). There is some kind of block in memory
and you want to store both heap and stack there, and you are not sure, how big they both can grow during
runtime.
You can set aheappointer to the beginning of the block, then you can set astackpointer to the end of the
block (heap + size_of_block), and then you can addressnthelement of stack likestack[-n]. For example,
stack[-1]for 1st element,stack[-2]for 2nd, etc.
This will work in the same fashion, as our trick of addressing string from the end.
You can easily check if the structures has not begun to overlap each other: just be sure that address of
the last element inheapis below the address of the last element ofstack.
Unfortunately,− 0 as index will not work, since two’s complement way of representing negative numbers
(2.2 on page 452) don’t allow negative zero, so it cannot be distinguished from positive zero.
This method is also mentioned in “Transaction processing”, Jim Gray, 1993, “The Tuple-Oriented File Sys-
tem” chapter, p. 755.