[英]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.