繁体   English   中英

设置指向静态2D数组的指针

[英]Set a pointer to a static 2D array

如何在类中将指针设置为外部静态数据结构?

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);

使用此代码,我得到以下编译时错误消息(Visual C ++ 2008/2012):

1>错误C2440:“ =”:无法从“双精度[3] [5]”转换为“双精度**”
1>指向的类型无关; 转换需要reinterpret_cast,C样式强制转换或函数样式强制转换
1>请参见对正在编译的函数模板实例化'void S :: Init4 <3,5>(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;
    }
}

另一种(可能更好)的解决方案是向struct Str添加模板参数,以替换nx / ny ,然后matr成员可以具有包含维的类型。

因此,您想要一个指向2D数组的指针。 Str必须是一个模板,因为它的类型的成员matr取决于阵列的尺寸。

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM