Re: arrays, malloc

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


Date: Sat, 06 Mar 2004 17:09:53 -0600

Kyle 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
>enough space betwean them ...
>am i correct ?

For the single-block approach, the allocation would be something like:

int** p = (int*) malloc(
      num_rows*sizeof(int*)
     +whatever padding is necessary
     +num_rows*num_cols*sizeof(int));

Then the memory for an array int[3][2] would be arranged as follows, with p
pointing at location 00:

00: pointer to row 0 (offset 16)
04: pointer to row 1 (offset 24)
08: pointer to row 2 (offset 32)
12: ... padding if any (none needed here)
16: p[0][0]
20: p[0][1]
24: p[1][0]
28: p[1][1]
32: p[2][0]
36: p[2][1]

While the syntax for accessing p[row][col] is the same as for a true 2D
array, do note that a true 2D array doesn't have an array of pointers.
Instead, it consists solely of the array data, which above extends from
offset 16 on.

-- 
Doug Harrison
Microsoft MVP - Visual C++


Relevant Pages

  • [RFC][PATCH] flexible array implementation v4
    ... I call it a flexible array. ... so never does an order>0 allocation. ... storage for pointers to the second level. ... all locking must be provided by the caller. ...
    (Linux-Kernel)
  • Re: [RFC][PATCH] flexible array implementation v4
    ... I call it a flexible array. ... so never does an order>0 allocation. ... storage for pointers to the second level. ... all locking must be provided by the caller. ...
    (Linux-Kernel)
  • Re: FSL auxiliary files: proposed reorganization of words
    ... For dynamic arrays/matrices which have not been allocated, the value of addr is ambiguous. ... It is the programmer's responsibility to ensure that he/she doesn't attempt to use a dynamic array prior to allocation. ... If the header block structure is allowed to be implementation dependent, then provide an API function which returns the start of the header block. ...
    (comp.lang.forth)
  • [RFC][PATCH] flexible array implementation v3
    ... I call it a flexible array. ... so never does an order>0 allocation. ... storage for pointers to the second level. ... all locking must be provided by the caller. ...
    (Linux-Kernel)
  • Re: Newbie on the lose.. How to add an unknown length dataset to an array
    ... allocation, it does require enough virtual memory to hold twice the ... consisting of one of these records plus a pointer. ... Having read all the data into the list, I know the size of the array ... and your pointer method makes good sense from since it dosen't ...
    (comp.lang.fortran)

Loading