clang ++无法使用类型为'int(*)[dim2]'的右值初始化类型为'int(*)[dim2]'的变量 [英] clang++ cannot initialize a variable of type 'int(*)[dim2]' with an rvalue of type 'int (*)[dim2]'
问题描述
为什么要输入代码
void fcn(int *twoDArrayPtr, const int dim1, const int dim2) {
int (*array)[dim2] = reinterpret_cast<int (*)[dim2]>(twoDArrayPtr);
}
int main() {
return 0;
}
产生编译器错误
error: cannot initialize a variable of type 'int (*)[dim2]' with
an rvalue of type 'int (*)[dim2]'
类型相同,所以我认为可以执行分配.由于 int(*)[dim2]
是指向大小为 dim2
的数组的指针,因此可以是指向一堆大小为 dim2
在指针可索引的连续内存中,我认为这应该可行.
The types are the same, so I'd think the assignment can be performed. Since int (*)[dim2]
is a pointer to an array of size dim2
and as such could be a pointer to a bunch of arrays of size dim2
in contiguous memory indexable by the pointer, I would think this should work.
我在Mac OS/X上使用clang ++,具有以下版本信息:
I'm using clang++ on Mac OS/X with the following version information:
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
推荐答案
dim2
不是编译时常量,并且C ++中不存在VLA(可变长度数组).其他一些编译器(例如gcc)具有语言扩展,以允许C ++中的VLA,但是clang的行为符合标准.
dim2
is not a compile-time constant, and VLAs (variable-length arrays) don't exist in C++. Some other compilers (such as gcc) have language extensions to allow VLAs in C++, but clang's behavior is standard-conforming.
您可以使用为您进行地址翻译的类(或类模板)来解决该问题,例如
You can work around the problem with a class (or class template) that does the address translation for you, such as
// This is very rudimentary, but it's a point to start.
template<typename T>
class array2d_ref {
public:
array2d_ref(T *p, std::size_t dim) : data_(p), dim_(dim) { }
T *operator[](std::size_t i) { return &data_[i * dim_]; }
private:
T *data_;
std::size_t dim_;
};
...
array2d_ref<int> array(twoDArrayPtr, dim2);
但是,除非您在编译时就知道数组的尺寸,否则恐怕不可能(便携地)拥有指向数组的指针.
But I'm afraid it is not possible (portably) to have a pointer-to-array unless you know the dimension of the array at compile time.
这篇关于clang ++无法使用类型为'int(*)[dim2]'的右值初始化类型为'int(*)[dim2]'的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!