Re: arrays, malloc
From: Barry Schwarz (schwarzb_at_deloz.net)
Date: 03/06/04
- Next message: Doug Harrison [MVP]: "Re: arrays, malloc"
- Previous message: Doug Harrison [MVP]: "Re: arrays, malloc"
- In reply to: Kyle: "Re: arrays, malloc"
- Next in thread: Barry Schwarz: "Re: arrays, malloc"
- Messages sorted by: [ date ] [ thread ]
Date: 6 Mar 2004 23:21:10 GMT
On Sat, 6 Mar 2004 23:39:45 +0100, "Kyle" <a@b.c> wrote:
>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
That should be *(array+1). Make life easy on yourself and use the
equivalent subscript notation array[1].
>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++
>
<<Remove the del for email>>
- Next message: Doug Harrison [MVP]: "Re: arrays, malloc"
- Previous message: Doug Harrison [MVP]: "Re: arrays, malloc"
- In reply to: Kyle: "Re: arrays, malloc"
- Next in thread: Barry Schwarz: "Re: arrays, malloc"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|