C++ 设置指向静态二维数组的指针

C++ 设置指向静态二维数组的指针,c++,arrays,pointers,C++,Arrays,Pointers,如何在类中设置指向外部静态数据结构的指针 struct Str { double **matr; // which type should matr be? int nx, ny; template<size_t rows, size_t cols> void Init(double(&m)[rows][cols], int sx, int sy) { matr = m; // <-- error

如何在类中设置指向外部静态数据结构的指针

struct Str {
    double **matr;   // which type should matr be?
    int nx, ny;

    template<size_t rows, size_t cols>
    void Init(double(&m)[rows][cols], int sx, int sy) {
        matr = m;     // <-- error
        nx = sx; ny = sy;
    }
};
...
static double M[3][5] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
                          { 0.1, 1.1, 2.1, 3.1, 4.1 },
                          { 0.2, 1.2, 2.2, 3.2, 4.2 } };
Str s;
s.Init(M, 3, 5);
结构Str{ double**matr;//matr应该是哪种类型? 纽约州奈斯; 模板 void Init(双(&m)[行][cols],整数sx,整数sy){ matr=m;//错误C2440:“=”:无法从“double[3][5]”转换为“double**”
1> 指向的类型是不相关的;转换需要重新解释类型转换、C样式转换或函数样式转换

1> 请参阅正在编译的函数模板实例化“void S::Init4(double(&)[3][5],int,int)”的参考。问题在于
double
的2D数组不是指针数组,它只是指向2D数组的第一个元素的单个指针,该数组由内存中多个连续的double行表示

由于您的
struct
具有字段
nx
/
ny
,因此您可以将数组转换为简单指针,然后使用
nx
/
ny
访问它,即:

struct Str {
    double *matr;
    int nx, ny;

    void Init(double* m, int sx, int sy) {
        matr = m;
        nx = sx; ny = sy;
    }
};

static double M[3][5] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
                          { 0.1, 1.1, 2.1, 3.1, 4.1 },
                          { 0.2, 1.2, 2.2, 3.2, 4.2 } };

int main() {
    Str s;
    s.Init(M[0], 3, 5);
    return 0;
}
然后,您必须使用
nx
/
ny
来访问阵列,例如,可以将以下函数添加到打印阵列的
struct Str

#include <iostream>

void print() {
    for (int i = 0; i < nx; i++) {
        for (int j = 0; j < ny; j++) {
            std::cout << matr[i*ny+j] << " ";
        }
        std::cout << std::endl;
    }
}
#包括
作废打印(){
对于(int i=0;istd::cout因此,您希望有一个指向2D数组的指针。
Str
必须是一个模板,因为其成员的类型取决于该数组的维度

template<int rows, int cols>
struct Str {
    double (*matr)[rows][cols];

    void Init(double(&m)[rows][cols]) {
        matr = &m;
    }
};

Str<3, 5> s;
s.Init(M);
模板
结构Str{
双(*matr)[行][cols];
void Init(双(&m)[行][cols]){
matr=&m;
}
};
strs;
s、 Init(M);

您对
M
的过度使用可能会让人感到困惑-您有
M
的静态数组
double
M
用于
void Str::Init()
函数的模板参数。您打算使用哪一个
double(*M)[M]参考?我想你希望你的
mattr
是简单的
double*mattr
,或者可能是更丑陋的
double(*mattr)[5]
…@twalberg-谢谢,我修好了。double(*m)[S]意思?它是一个函数指针数组吗?@Cool_Coder-它是一个2D数组。现在应该更清楚了。好吧,那么问题出在哪里?它不是编译吗?如果我在结构中使用模板参数,我必须在定义对象时指定尺寸。我可以使用成员函数上的模板来选择以后调整对象的大小吗?参考:用户2079303的答案。