Is it safe to set up a bunch of dedicated pointer to a pointer to a VLA?

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.

+6
source share
1 answer

cols behavior if cols is 0 or less. C11 provided support for VLA optionally (see, for example, here , and you noted your question C99 where they are needed), if theyre not supported, the __STDC_NO_VLA__ macro __STDC_NO_VLA__ defined as 1 (see C11 6.10.8.3 p1).

That aside, you are safe.

Thanks to Wah and Alter Mann!

+4
source

Source: https://habr.com/ru/post/973097/


All Articles