www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/04/04/14:16:44

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Dynamic Allocation of Multidimensional Arrays
Date: Fri, 04 Apr 1997 09:41:26 -0800
Organization: Alcyone Systems
Lines: 44
Message-ID: <33453D46.64638A66@alcyone.com>
References: <33448D13 DOT 664 AT ucsu DOT Colorado DOT edu> <334480FA DOT 22D9 AT cs DOT com>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

John M. Aldrich wrote:

> In C, you can just dynamically allocate a linear block of memory and
> index it just like you would the screen memory.  For example:
> 
> unsigned char *buffer;
> 
> buffer = calloc( sizeof(char) * SCREEN_WIDTH * SCREEN_HEIGHT );
> ...
> buffer + x + SCREEN_WIDTH * y = pixel;
>   -or-
> buffer[x + SCREEN_WIDTH * y] = pixel;
> 
> When you're done with it, be sure to free the buffer.  I can't imagine
> that you'd do things much differently iin C++.

The way to get "proper" dynamic multidimensional arrays in C (or C++) is
with a pointer to a pointer, each of which points to an array (itself a
pointer).  Like this (I'll use C++):

    int **aa; // This is going to be our two-dimensional array

    aa = new int *[x];

    for (int i = 0; i < x; i++)
         aa[i] = new int[y];

Now you can access aa as if it were a two-dimensional array:

    z = aa[i][j];

or

    aa[i][j] = z;

For C, just replace the news with appropriate calls to malloc.

-- 
       Erik Max Francis, &tSftDotIotE / email:  max AT alcyone DOT com
                     Alcyone Systems /    web:  http://www.alcyone.com/max/
San Jose, California, United States /    icbm:  37 20 07 N  121 53 38 W
                                   \
                          "E pur, / sic muove!"
                                 / Galileo Galilei

- Raw text -


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