将堆分配的指针转换为指向VLA的指针是否安全? [英] Is it safe to cast a heap allocated pointer to a pointer to a VLA?
问题描述
如果我有一个指向一些堆分配空间的指针,该空间代表一个典型的 行主要的二维数组,是否可以安全地将此指针强制转换为 VLA的等效指针,以便于进行子脚本编写?示例:
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?
万一有人想知道,这里的用例是我正在从 代表行主要2D(或3D)数组的文件/套接字/等,我想使用 VLA避免了手动计算元素索引.
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.
推荐答案
如果cols
为0或更小,则行为未定义. C11将对VLA的支持设为可选(例如,参见此处,并标记了问题C99(在需要的地方),如果不支持,则将宏__STDC_NO_VLA__
定义为1(参见C11 6.10.8.3 p1).
The behaviour is undefined if cols
is 0 or smaller. C11 made support for VLAs optional (see e.g. here, and you tagged your question C99, where they’re required), if they’re not supported, the macro __STDC_NO_VLA__
is defined to 1 (cf. C11 6.10.8.3 p1).
此外,您很安全.
感谢Ouah和Alter Mann!
Thanks to Ouah and Alter Mann!
这篇关于将堆分配的指针转换为指向VLA的指针是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!