delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/18/12:33:41

Date: Tue, 18 Aug 1998 18:33:06 +0200
From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Message-Id: <199808181633.SAA19318@acp3bf.physik.rwth-aachen.de>
To: max AT alcyone DOT com (Erik Max Francis)
Cc: djgpp AT delorie DOT com
Subject: Re: positive ints and arrays
Newsgroups: comp.os.msdos.djgpp
Organization: RWTH Aachen, III. physikalisches Institut B

[This whole thread is rather off-topic, here. It would normally belong
to comp.lang.c or comp.lang.c.moderated. It's a FAQ there,
actually...]

In article <35D9A4FC DOT 1709C5CA AT alcyone DOT com> you wrote:
> Endlisnis wrote:

> > If you need more than one dimension to be
> > dynamic, then you have to 'fake-it'.  If you want something NxM, then:
> > char* Array = new /* or malloc */ [N*M];
> > Array[X*N+Y];  //To access Array[X][Y].

> Not true.  You can first allocate a array of pointers to the data type,
> and then for each element of the array allocate arrays of the data type
> and assign it to that index.  That gives you a fully-dynamic two
> dimensional array, but in addition requires N + 1 pointers and N + 1
> allocations.

Actually, you can easily get along with only 2 allocations, like this:

mytype ** twod_array = malloc(n*sizeof(mytype *));
twod_array[0] = malloc(n*m*sizeof(mytype));
for (i=1; i<m; i++) 
  twod_array[i] = twod_array[0]+m*i;

This method has the additional benefit that you can use *both* access
methods:

	twod_array[0][x*m+y]
	twod_array[x][y] 

These are both valid ways to access elements of this two-dimensional
array.  For more details, see the FAQ of comp.lang.c.

--
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019