Malloc and arrays...

Chris Torek torek at elf.ee.lbl.gov
Mon Mar 4 09:40:39 AEST 1991


In article <1991Mar3.172942.3116 at nntp-server.caltech.edu>
eychaner at suncub.bbso.caltech.edu writes:
>Warm up those flame guns!  It's time for Another Novice Question!

Ah, but you at least checked the FAQ and thought a bit before you posted :-)

>[I can malloc a `1D array' but] how can I access it as a 2D array, like so:
>  bigmemory [RIGHT_HERE][RIGHT_NOW] = SOME_CHARACTER;
>I know I could use, for example:
>  *(bigmemory + RIGHT_HERE * SIZEOF_RIGHTNOW + RIGHT_NOW) = SOME_CHARACTER;
>but all my previous code (which uses the 2D array) would then have to be
>changed.  And it looks much nicer (when RIGHT_HERE and RIGHT_NOW are big,
>nasty expressions) in 2D array format.

Presumably `SIZEOF_RIGHTNOW' is an integer constant and will never
change (i.e., is fixed by the design; the algorithm only works on
M-by-31 arrays or some such).  For the following discussion, let us say
it is a `#define N 31'.  (It must in fact be some integer constant in
the `previous code' since C arrays must have fixed, integral sizes.)

Then:

	char (*p)[N];

declares p as a `pointer to array 31 of char'.  This means that p can
point to an `array 31 of char'; but moreover, just as `char *bigmemory'
can point to more than one of its base type (char), so too `p' can point
to more than one of its base type (array 31 of char).  If you want M
such arrays, all contiguous:

	p = (char (*)[N])malloc(M * sizeof *p);
	if (p == NULL) die("out of memory");

(or `p = (char (*)[N])malloc(M * sizeof(char [N]));' or ...malloc(M * N *
sizeof(char)) or malloc(M * N * 1) or malloc(M * N); these are all
equivalent).  Once you have done this:

	p[i][j]

(where 0 <= i < M and 0 <= j < N) is an individual `char'.  This works
because p[i] names the i'th object to which p points, i.e., the i'th
`array 31 of char'.  This array appears in a value context, so The Rule
applies; we take the corresponding `pointer to char' (which points to
the first character in the i'th `array 31 of char') and name its j'th
object.

Now, if the reason you are changing the code is that N is *not* a fixed
integer constant, all of this goes out the window.  Someone else has
posted a row-vector solution (and others appear in the FAQ), so I will
stop here.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab EE div (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list