跳入具有可变修改类型的标识符

跳入具有可变修改类型的标识符

This question already has answers here:
Closed 5 years ago.
C : stack memory, goto and “jump into scope of identifier with variably modified type”,
(3个答案)
下面的代码是否应该产生编译时错误:“跳入具有可变修改类型的标识符的范围”?我可以理解为什么C99标准有这个约束,如果数据是动态保留在堆栈上的。但我不明白当声明从堆的简单强制转换为动态分配的块时会出现什么问题。
void ShowVariablyModifiedTypeBug(void)
{
    int rowCount = 2;
    int colCount = 5;
    int elementCount = rowCount * colCount;

    void *dataPtr = malloc(sizeof(int) * elementCount);
    if (!dataPtr) goto exit;
    int (*dataArr)[colCount] = (int (*)[colCount])dataPtr;

exit:
    return;
}

最佳答案

如R.Sahu的评论所述,SO问题显然不符合标准。

C99 standard, paragraph 6.8.6.1

Constraints

[...] A goto statement shall not jump from outside the scope of an identifier
having a variably modified type to inside the scope of that identifier.

https://stackoverflow.com/a/20654413/434551中所述,可以通过创建子作用域来避免错误:“跳入具有可变修改类型的标识符的作用域”:
void ShowVariablyModifiedTypeBug(void)
{
    int rowCount = 2;
    int colCount = 5;
    int elementCount = rowCount * colCount;

    void *dataPtr = malloc(sizeof(int) * elementCount);
    if (!dataPtr) goto exit;

    {
    int (*dataArr)[colCount] = (int (*)[colCount])dataPtr;
    }

exit:
    return;
}

10-05 19:28