Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!rutgers!bellcore!texbell!merch!sneaky!gordon From: gordon@sneaky.TANDY.COM (Gordon Burditt) Newsgroups: comp.lang.c Subject: Re: Contiguous Arrays Message-ID: <7799@sneaky.TANDY.COM> Date: 23 Feb 89 09:13:26 GMT References: <2508@ssc-vax.UUCP> <8943@alice.UUCP> <1828@valhalla.ee.rochester.edu> Reply-To: gordon@sneaky.UUCP (Gordon Burditt) Organization: Gordon Burditt Lines: 46 >On a similar note, just yesterday a friend and I were discussing >tricks to access arrays with different ranges. >For instance, if the array was to be x[101] to x[110] instead of >x[0] to x[9], what is the easiest way to do it? >For automatic arrays one could do >int space[10], *x; >x = &space[0] - 101; UNPORTABILITY ALERT! There is no guarantee that there is a way to represent &space[0] - 101 at all. Further, computing it may cause overflows such that (&space[0] - 101) + 101 != &space[0] It could happen that (&space[0] - 101) == (int *) NULL. Even computing &space[0] - 101 could cause core dumps (MSDOS equivalent: hang system forcing use of RESET, optionally trashing FAT on hard disk) On *86 machines, consider what happens when space starts within 100 bytes of physical address 0. Having it within 100 bytes of the data segment origin may cause problems also. These problems may vary with model, load address, and the phase of the moon. Given the declaration: int space[10]; then &space[i] has guaranteed meaning when i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, or 10, and no other values of i. You can't use space[10] because it's out of range, but &space[10] is guaranteed to have a representation by the ANSI standard. struct foobar space[10], *x; /* Right */ for (x = &space[0]; x < &space[10]; x++) x->data = 0; /* Wrong - this loop may never execute */ for (x = &space[9]; x > &space[-1]; x--) x->data = 0; I got bit on a loop like the above on a 68000. As it happened, &space[0] was less than sizeof(struct foobar), so &space[-1] was positive and very large. Since &space[9] < &space[-1], the loop never executed. Gordon L. Burditt ...!texbell!sneaky!gordon