Re: arrays, malloc
From: Kyle (a_at_b.c)
Date: 03/06/04
- Next message: Barry Schwarz: "Re: arrays, malloc"
- Previous message: Doug Harrison [MVP]: "Re: arrays, malloc"
- In reply to: Doug Harrison [MVP]: "Re: arrays, malloc"
- Next in thread: Doug Harrison [MVP]: "Re: arrays, malloc"
- Reply: Doug Harrison [MVP]: "Re: arrays, malloc"
- Reply: Barry Schwarz: "Re: arrays, malloc"
- Messages sorted by: [ date ] [ thread ]
Date: Sat, 6 Mar 2004 23:39:45 +0100
you mean by this, that i should malloc big chunk of mem, set some
int** array;
to the value i got, and afterwards, set each
*array , (*array+1), ... to a proper value from my allocated chunk with
enough space betwean them ...
am i correct ?
"Doug Harrison [MVP]" <dsh@mvps.org>
news:tggk40tgkb0tpps97egam56i6a6dq4sd9l@4ax.com...
> 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: Barry Schwarz: "Re: arrays, malloc"
- Previous message: Doug Harrison [MVP]: "Re: arrays, malloc"
- In reply to: Doug Harrison [MVP]: "Re: arrays, malloc"
- Next in thread: Doug Harrison [MVP]: "Re: arrays, malloc"
- Reply: Doug Harrison [MVP]: "Re: arrays, malloc"
- Reply: Barry Schwarz: "Re: arrays, malloc"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|