Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!uwm.edu!ux1.cso.uiuc.edu!tank!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: A pointer to a 3-D array, or an array of ptrs to 2-D arrays? Message-ID: <20773@mimsy.umd.edu> Date: 15 Nov 89 13:48:32 GMT References: <2765@levels.sait.edu.au> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 44 In article <2765@levels.sait.edu.au> MARWK@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@cs.umd.edu Path: uunet!mimsy!chris