A pointer to a 3-D array, or an array of ptrs to 2-D arrays?
Chris Torek
chris at mimsy.umd.edu
Thu Nov 16 00:48:32 AEST 1989
In article <2765 at levels.sait.edu.au> MARWK at levels.sait.edu.au writes:
>Why does (1) work but (2) does not?
>(1) p = (int (*) [13][2][64]) malloc (sizeof(int) * 13 * 2 * 64)
> *p[i][j][k] = 6
>(2) p = (int (*) [2][64]) malloc (sizeof(int) * 13 * 2 * 64)
> p[i][j][k] = 6
(I think you have this backwards: (1) fails and (2) works)
>These are both supposed to be ways of dynamically creating a 3-dimensional
>array for accessing as such, but (1) causes a segmentation error when run
>on the ENCORE.
(Aha, you think you have it backwards too :-) )
You need to read my recent treatises on `pointers and arrays'.
The short explanation for the failure of (1):
*p[i][j][k]
is the same as
*(((p[i])[j])[k])
which is the same as
p[i][j][k][0]
which means to add i*sizeof(*p) to p, which will add i*13*2*64*sizeof(int)
bytes to whatever value is in p, which, if i is more than 0, will be
outside of the region allocated by malloc.
The code in (2) is much more `C-like': p is a pointer to an array 2
of array 64 of int, which points to the first of 13 consecutive such
things. In (1), p is a pointer to an array 13 of array 2 of array 64
of int, and it points to the first of one such thing, so you must always
write (*p) or (p[0]) in order to get to that thing before you can
do anything useful with it.
(All of the above assumes p is properly declared.)
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris at cs.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list