Lately, I’ve been writing a lot of C code and using large multidimensional arrays. I’ve found that using a simple macro to map a 1D array to a 2(or more)D array has simplified my code and may make my code marginally faster.
Macro:
#define DATA(r, c) (data[(r)*width + (c)])
Accessing the array:
DATA(rowNdx, colNdx) = x;
Why
- Only need to
mallocandfreeonce(malloc(sizeof(char) * width * height)instead ofmallocing for each row of the array - Since the preprocessor handles the macro, there isn’t any extra overhead of function calls
- Array access is terse and it’s very clear what is going on - instead of
arr[x][y], you havearr(x,y)