Defining a pointer to an array
Terry Bartsch
a1082 at mindlink.UUCP
Fri Sep 22 21:11:39 AEST 1989
I have found it convenient to use a large 4-dimensional array in an interactive
program and must malloc the space to reduce object module size. This caused me
to discover the following peculiarity:
The construct "int y[a][b][c][d]"
allocates a*b*c*d integers in the form of an array.
-----
"ANSI" K&R and the Microsoft Systems Journal each show a one-dimensional
example of "a pointer to an array".
The construct "int (*x) [a][b][c][d]"
should theoretically allocate a pointer to the same sort of array.
-----
However, when the expression is resolved, the [d] position is multiplied by
"d*sizeof(int)" rather than by "sizeof(int)" and the other indexes also are
multiplied by oversized figures, causing the pointer to exceed actual allocated
memory with very small subscripts and preventing usage of a construct such as
"for (n = 0; n < a*b*c*d; x[0][0][0][n] = 0);"
The addresses are "miscalculated" right down to the trivial case of a
one-dimensional array.
I empirically determined that instead of "int (*x) [a][b][c][d]"
one must specify "int (*x) [b][c][d][1]". (!!?)
When defined as the latter, *x[][][][] acts exactly like a "normal" array
y[][][][] of the same dimensions whenever referenced in the program.
This occurs on both Turbo C (808x) and a public-domain C for the Amiga (680xx),
despite (supposedly) differing developers and integer size.
Does this make sense in terms of the definition of the language? Is there a
method of defining the pointer which is more intuitive?
More information about the Comp.lang.c
mailing list