将堆分配的指针强制转换为指向VLA的指针是否安全?

如果我有一个指向某个堆分配空间的指针,该空间代表一个典型的行主要二维数组,是否可以将此指针强制转换为指向VLA的等效指针以方便子脚本编写? 例:

// // 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"); } } 

我已经测试了上面的代码。 它似乎有效,对我来说它应该有用,但它是安全的,定义的行为吗?

如果有人想知道,这里的用例是我从文件/套接字/等接收代表行主要2D(或3D)数组的数据,我想使用VLA来避免手动计算索引到元素。

如果cols为0或更小,则行为未定义。 C11支持VLA可选(例如,参见此处 ,并且您在需要时标记了您的问题C99),如果它们不受支持,则宏__STDC_NO_VLA__被定义为1(参见C11 6.10.8.3 p1)。

除此之外,你是安全的。

感谢Ouah和Alter Mann!