Contiguous Arrays

Chris Torek chris at mimsy.UUCP
Thu Feb 23 16:22:38 AEST 1989


In article <830 at atanasoff.cs.iastate.edu> hascall at atanasoff.cs.iastate.edu
(John Hascall) writes:
>How about:
>
>Assume int's are (say) 2 bytes.  Assume further that your
>machine is stupid, and all accesses must be on an 8-byte boundary. ...
>
>	address (0x01000 base):   0 1 2 3 4 5 6 7 8 9 a b c d e f 0 1 ...
>	 x[?]                     0 0             1 1             2 2
>
>A non-contiguous array, and the compiler can always generate
>
>	p <- p + 8
>
>for p++; since it knows about the 8-byte alignment business.

The trick here is that it *appears* contiguous.  You cannot tell
(without stepping outside the bounds of the C language proper)
that there are holes.

A more interesting fact is that, because of the array-of-E /
pointer-to-E conversion rule, given a declaration like

	int x[3][2];

and such a compiler, you get this layout:

	addr:	0 1 2 3 4 5 6 7 8 9 a b c d e f 0 1 2 3 4 5 6 7 8 9 ...
		---		---		---		---
		 ^		 ^		 ^		 ^
	      x[0][0]	      x[0][1]	      x[1][0]	      x[1][1]

On a more typical machine, you get:

	addr:	0 1 2 3 4 5 6 7 8 9 a b
		--- --- --- --- --- ---
		0/0 0/1 1/0 1/1 2/0 2/1

If your compiler lets you get away with writing x[0][2]---if it does
not abort with a subscript range error---it will always do it by
talking to x[1][0].  (If C did not have malloc, the compiler could
arrange things otherwise.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list