本文介绍了转换为运行时确定的大小数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准是否允许此类型转换?我能够使用g ++ 5.4(在linux上运行)进行编译,但无法使用g ++ 4.2(在OSX上运行)进行编译.

Is this cast allowed by C++ standard? I was able to compile it with g++ 5.4 (running in linux), but not with g++ 4.2 (running in OSX).

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

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

'width' is an integer determined in runtime. g++ 4.2 throws:

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

这对我没有任何意义.

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

(PS: I was actually surprised when this first compiled)

编辑

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

Small code that compiles in 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的注释所示,它可以在g ++ 4.1中进行编译.但是,它无法在clang中编译,并抛出了我之前提到的相同错误:

The Mac that couldn't compile this with g++4.2 is not with me now, so I can't reproduce the error. As shown in the comments by @xskxzr with Compiler Explorer, it compiles in g++4.1. However, it doesn't compile in clang, throwing the same error I stated earlier:

<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

问题是:

该输出错误如何解释?

OS X的g ++版本是否可能完全不同?

Is it possible that g++ versions are quite different for OSX?

推荐答案

在Mac上,编译失败可能是由于Clang错误(所以 g ++ 在此处运行Clang而不是GCC).之前已经观察到过:

The compilation failure on the Mac is probably due to a a Clang bug (so g++ ran Clang there, not GCC). It has been observed before:

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

Variable length arrays are a GNU extension to C++, and Clang is supposed to support it, too.

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

At least on some versions of Clang, it is possible to get this to compile by introducing an explicit typedef for the variable length array type:

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

这篇关于转换为运行时确定的大小数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:28