Search code examples
arrayscmatrixmallocdynamic-memory-allocation

2D Math Matrix with Malloc


I know a similar question is already asked here for example:

Malloc a 2D array in C

However, my question is not how to create one but rather if I should prefer to use for a mathematical 2D matrix a "real" 2D array (with pointers of pointers) or rather a flattened 1-dimensional array with proper indexing.


Solution

  • I think the only case it can be important is when you are doing operations that depends on the neighbors of the matrix. In this case, using a 2D matrix is a bit better because it avoids cache misses.

    This is specially important for problem solutions that use dynamic programming optimization .

    I believe it can also be important for image processing, where many operations are applied in a rectangle of pixels.