If I have a pointer to some heap-allocated space representing a typical array of two-dimensional arrays, is it safe to point to an equivalent VLA pointer 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 checked the code above. This seems to work, and it makes sense to me that it should work, but how safe is the behavior defined?
In case someone wonders, here is a usage example: I get data from a file / socket / etc representing a 2D (or 3D) array with a large string, and I would like to use VLA to avoid manually calculating the indexes for the elements.
source share