void compute(int rows, int columns, double *data) {
double (*data2D)[columns] = (double (*)[columns]) data;
// do something with data2D
}
int main(void) {
double data[25] = {0};
compute(5, 5, data);
}
Sometimes, it'd be very convenient to treat a parameter as a multi-dimensional array, but it needs to be declared as a pointer into a flat array. Is it safe to cast the pointer to treat it as a multidimensional array, as compute
does in the above example? I'm pretty sure the memory layout is guaranteed to work correctly, but I don't know if the standard allows pointers to be cast this way.
Does this break any strict aliasing rules? What about the rules for pointer arithmetic; since the data "isn't actually" a double[5][5]
, are we allowed to perform pointer arithmetic and indexing on data2D
, or does it violate the requirement that pointer arithmetic not stray past the bounds of an appropriate array? Is data2D
even guaranteed to point to the right place, or is it just guaranteed that we can cast it back and recover data
? Standard quotes would be much appreciated.