delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/06/21/06:42:06

Date: Mon, 21 Jun 1999 12:41:19 +0200
From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Message-Id: <199906211041.MAA09469@acp3bf.physik.rwth-aachen.de>
To: djgpp AT delorie DOT com
Subject: Re: Dinamic allocation
Newsgroups: comp.os.msdos.djgpp
Organization: RWTH Aachen, III. physikalisches Institut B
X-Newsreader: TIN [version 1.2 PL2]
Reply-To: djgpp AT delorie DOT com

In article <LOBBKLEPLBKLOKFELHOIAELLCCAA DOT djgpp AT niemeyer DOT net> you wrote:

> I'm still look for a way to allocate arrays with 2
> or more indexes. 

The basic trick is that there is no such thing as a multi-dimensional
array in C. There are only one-dimensional arrays, but you can have an
array of arrays, as a replacement of multidimensional arrays.

Now, if you want the array to be dynamic (i.e. you can choose the size
of all the dimensions at run-time of the program), you're not really
talking about arrays, any more. It's *pointers*, now. Pointers can
also be accessed using the traditional array notation a[i]. Pointers
to pointers can thus be accessed by a[i][j], too. That's what the
first poster suggested, effectively:

	char **store = malloc(height * sizeof(char *));
	for (i=0; i<height; i++)
	  store[i] = malloc(width * sizeof(char));

This method will allow you to access store[i][j], just like you
normally would.

The other method is to forget about writing a[i][j], and use a single,
large block of memory, and compute the index manually, given 'i' and
'j':

	char *store = malloc(width*height* sizeof(char));

Now, instead of store[i][j], you'ld have to write store[i*height+j].


--
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