If I've got a pointer to some heap allocated space that represents a typical row-major two dimensional array, is it safe to cast this pointer to an equivalent pointer to a VLA for convenient sub-scripting? Example:
//
// Assuming 'm' was allocated and initialized something like:
//
// int *matrix = malloc(sizeof(*matrix) * rows * cols);
//
// for (int r = 0; r < rows; r++) {
// for (int c = 0; c < cols; c++) {
// matrix[r * cols + c] = some_value;
// }
// }
//
// Is it safe for this function to cast 'm' to a pointer to a VLA?
//
void print_matrix(int *m, int rows, int cols) {
int (*mp)[cols] = (int (*)[cols])m;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf(" %d", mp[r][c]);
}
printf("\n");
}
}
I've tested the code above. It seems to work, and it makes sense to me that it should work, but is it safe, defined behavior?
In case anyone is wondering, the use case here is I'm receiving data from a file/socket/etc that represents a row-major 2D (or 3D) array and I'd like to use VLA's to avoid manually calculating indexes to the elements.