转换为指向运行时确定大小的数组的指针

Cast to pointer to array of runtime-determined size

C++ 标准允许这种类型转换吗?我可以使用 g++ 5.4(运行 in linux)编译它,但不能使用 g++ 4.2(运行 in OSX)。

char* ptr;
char (*img)[width][3] = (char (*)[width][3])ptr;

'width' 是在运行时确定的整数。 g++ 4.2 抛出:

cannot initialize a variable of type 'char (*)[width][3]'
  with an rvalue of type 'char (*)[width][3]'

这对我来说没有任何意义。

(PS: 第一次编译的时候我真的很惊讶)

编辑

在g++5.4中编译的小代码

#include <iostream>
int main(){
    char* ptr;
    int width;
    std::cin >> width;
    char (*img)[width][3] = (char (*)[width][3])ptr;
}

无法用g++4.2编译的Mac现在不在我身边,所以我无法重现错误。正如@xskxzr 对 Compiler Explorer 的评论中所示,it compiles in g++4.1. However, it doesn't compile in clang,抛出了我之前提到的相同错误:

<source>:9:12: error: cannot initialize a variable of type 'char (*)[width][3]' with an rvalue of type 'char (*)[width][3]'
    char (*img)[width][3] = (char (*)[width][3])ptr;
           ^                ~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
Compiler returned: 1

问题是:

如何解释输出错误?

OSX 的 g++ 版本可能完全不同吗?

Mac 上的编译失败可能是由于 Clang 错误(所以 g++ 运行 那里是 Clang,而不是 GCC)。之前观察过:

可变长度数组是 C++ 的 GNU 扩展,Clang 应该也支持它。

至少在某些版本的 Clang 上,可以通过为可变长度数组类型引入显式 typedef 来编译它:

typedef int (*vla)[width][3];
vla img = (vla) ptr;