Bifalgorithm post · Computer science one · Contiguous 2-D Arrays

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

Why use a contiguous memory block for a two-dimensional array? (Computer science one · Contiguous 2-D Arrays) — "The example depicted in Figure 20.1 constructs…

Ideas in this flowchart

  • Constructing a two-dimensional array with contiguous memory
  • The example initially constructs a two-dimensional array.
  • Each row is created by an independent call to malloc().
  • The rows may occupy non-contiguous memory blocks.
  • Non-contiguous rows are generally not a problem because malloc() is usually efficient.
  • Some scenarios may benefit from one contiguous memory block.
  • Contiguous storage can be achieved with one malloc() call and pointer manipulation.
  • The initial malloc() for the pointer-to-pointers setup remains unchanged.
  • Repeated allocations inside a for loop are replaced by one allocation.
  • The single allocation requests enough bytes for the entire n × m array.
  • The allocated result is stored at the beginning of the array, at index zero.
Feed/

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

No cover

Channel

Computer science one

1 page

"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)."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.