Re: arrays, malloc
From: Doug Harrison [MVP] (dsh_at_mvps.org)
Date: 03/06/04
- Next message: Kyle: "Re: arrays, malloc"
- Previous message: Kyle: "arrays, malloc"
- In reply to: Kyle: "arrays, malloc"
- Next in thread: Kyle: "Re: arrays, malloc"
- Reply: Kyle: "Re: arrays, malloc"
- Messages sorted by: [ date ] [ thread ]
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++
- Next message: Kyle: "Re: arrays, malloc"
- Previous message: Kyle: "arrays, malloc"
- In reply to: Kyle: "arrays, malloc"
- Next in thread: Kyle: "Re: arrays, malloc"
- Reply: Kyle: "Re: arrays, malloc"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|