clang++ cannot initialize a variable of type 'int(*)[dim2]' with an rvalue of type 'int (*)[dim2]'

前端 未结 3 1390
南笙
南笙 2021-01-27 12:31

Why does the code

void fcn(int *twoDArrayPtr, const int dim1, const int dim2) {
    int (*array)[dim2] = reinterpret_cast(twoDArrayPtr);
}

         


        
3条回答
  •  囚心锁ツ
    2021-01-27 13:01

    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
    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 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.

提交回复
热议问题