Hacker News new | ask | show | jobs
by advocaat23 4355 days ago
I think it's always weird how multi-dimensional arrays are implemented in most C programming books. Do you guys really use a pointer-pointer approach to represent them? Because nowadays I always allocate a flat array and just calculate the indices. E.g.

  struct dmatrix {
    size_t rows, cols;
    double *data;
  }
and then a simple

  double dmatrix_get(struct dmatrix *m, size_t r, size_t c) {
    return m->data[r * m->cols + c];
  }
is all you need? In particular I find explicit array sizes in function headers very contrived and I have never used them in serious code. Normally it's just a pointer and a length argument similar to e.g. read/write functions in the standard library.
1 comments

I actually believe this is the preferable approach for performance portability reasons. It's easier to reason about cache /vectorization performance across architectures and compilers when dealing with a single pointer and calculated indices. If you absolutely have to have a pointer to say the first element of a row (resp. column if using column major) you can always do this:

    double* dmatrix_get_row(struct dmatrix* m, size_t r){
     return &m->data[r*m->cols];
    }
A pointer-to-pointer approach I think is most suitable for an actual array-of-arrays, where the length of each subarray can be different. Then you store an array of pointers to the first element of each subarray, and if the data is contiguous you can use that to calculate lengths as well.