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
- How can you combine contiguous structure storage with indirect access?ComputerScienceOne · Arrays of Structures
- How does malloc() allocate memory for a dynamic array?ComputerScienceOne · Dynamic Memory
- How can an array of structure pointers make swapping structures more efficient?ComputerScienceOne · Arrays of Structures
- How do you use and validate a dynamically allocated array?ComputerScienceOne · Dynamic Memory
- What other memory allocation functions and pointer cast options does C provide?ComputerScienceOne · Dynamic Memory
- How do you create and use an array of structures in C?ComputerScienceOne · Arrays of Structures
- How do you deallocate dynamically allocated arrays?ComputerScienceOne · Using Arrays with Functions
- How do you access array elements safely in C?ComputerScienceOne · Basic Usage