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