Concept

Why use a contiguous memory block for a two-dimensional array?

ComputerScienceOne / Contiguous 2-D Arrays

"The example depicted in Figure 20.1 constructs a two dimensional array. However, each “row” of the array was created using an independent call to malloc() which may result in non-contiguous memory blocks (each row may not be located in the memory address immediately following the previous row). In general, this is not a problem for most situations (we can expect most implementations of malloc() to be efficient). However, it might be better in some scenarios if the two dimensional array were all one big block of contiguous memory. We can achieve this by a single call to malloc() and some clever pointer manipulation. We do this very similar to the previous example. Our first call to malloc() to set up the pointer-to-pointers is the same. However, instead of calling malloc() over and over in a for loop, we make one single call asking for a number of bytes to accommodate the entire n × m array. We then store the result at the “beginning” of the array (at index zero)."

Related Ideas

Why use a contiguous memory block for a two-dimensional array? | ComputerScienceOne | Bifalgorithm | Bifalgorithm