ftp.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/10/14:08:34

Date: Tue, 10 Feb 1998 20:07:07 +0100
From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Message-Id: <199802101907.UAA00439@acp3bf.physik.rwth-aachen.de>
To: jalex AT ea DOT oac DOT uci DOT edu (Jason Alexander)
Cc: djgpp AT delorie DOT com
Subject: Re: Dynamically declaring 2-d arrays
Newsgroups: comp.os.msdos.djgpp
Organization: RWTH Aachen, III. physikalisches Institut B

In article <34DF9744 DOT C7CFDBFE AT ea DOT oac DOT uci DOT edu> you wrote:
>   Can someone explain to me how to dynamically declare a 2-d array?

[Yes, this is slightly off-topic, but as the thread has already
started to grow, I'll just add my DM 0,02]

In addition to the explanations given by others, let me describe a
method that allows both kinds of access: explicit computation of an
address and the [][] notation. Let's allocate a dynamical 'char
a[n][m];':

char *a_inner = malloc(n*m*sizeof(char));
char ** a = malloc(n*sizeof(char *));

int i;
for (i=0; i<n; i++) 
  a[i] = a_inner + i*m;

This sets up a large, *contiguous* array a_inner, and a set of
pointers into that array. To access Element a[k][j], you can do any of
the following, whichever seems fit for the situation at hand:

	a[0][k*m+j];
	a_inner[k*m+j];
	a[k][j];

(BTW: I first learned about this from the comp.lang.c FAQ. If you don't
have that, go get it. It's about the most valuable source of information
you'll ever get about C in general, only second to the original work
itself: K&R2)

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