Re: arrays, malloc

From: Doug Harrison [MVP] (dsh_at_mvps.org)
Date: 03/06/04


Date: Sat, 06 Mar 2004 15:40:23 -0600

Kyle wrote:

>what's the easy way of malloc'ing 2 dimensional array
>
>i mean i may always do
>
>#define GET(array,i,j,size) array[i+size*j]

I'd understand that better if it was:

// Parens around macro params omitted for clarity
#define GET(p, row, col, num_cols)\
p[row*num_cols+col]

This provides the row-order indexing used for true multidimensional arrays.

>and use 1 dim array, but if it's (mallocing 2 dim) not too complicated i
>will be very happy <:

For both dimensions to vary, you have to allocate a 1D array and use
simulated indexing. If only the first dimension needs to vary, and you're in
C++, you can use:

int (*p)[some_constant] = new int[some_variable][some_constant];

If you can settle for a 2D array simulated as an array of pointers to
arrays, then you can use:

int** p = malloc(num_rows*sizeof(*p))

Then set each p[i] to:

p[i] = malloc(num_cols*sizeof(*p[i]));

Now you can get the natural p[row][col] syntax, at the cost of more
complicated memory management and more dereferencing. If you're really good,
you can do this all with one big allocation, that places the pointer array
and row subarrays all in one memory block. If you go that route, you should
pay careful attention to the alignment requirements of the element type; you
might need to insert some padding between the end of the pointer array and
the start of the row arrays.

-- 
Doug Harrison
Microsoft MVP - Visual C++


Relevant Pages

  • Re: Library Design, f0dders nightmare.
    ... demo mistake but I suggest to you that a sequence of blunders on this ... Feed it through your parser to get the offset of each ... offset to its appropriate place in the array of pointers and when you ... dividing the byte count by two to determine the maximum pointer array ...
    (alt.lang.asm)
  • Re: automatic arrays versus saved, allocated arrays
    ... advantage is that the automatic array is known to be contiguous. ... For an automatic array, the compiler can interate over the entire ... the automatic array and the allocated pointer array are contiguous. ...
    (comp.lang.fortran)
  • Re: arrays, malloc
    ... >> If you can settle for a 2D array simulated as an array of pointers to ... >> complicated memory management and more dereferencing. ... >> you can do this all with one big allocation, that places the pointer array ... >> and row subarrays all in one memory block. ...
    (microsoft.public.vc.language)
  • Is the syntax for multi-dimensional arrays counter-intuitive?
    ... means that there is an array of pointers to int with a size of 5, ... of whose elements is an array of int with a size of 3. ... Allocate memory for 5 pointers to int (i.e. pointer array) ...
    (comp.lang.c)
  • Re: question on reference to array slice
    ... array by looking it up in this pointer array. ... AREF => $aref, ... OFFSET => $offset, ...
    (comp.lang.perl.misc)