我已经摆脱了那些会分散注意力的代码。我要做的是为 3D 数组分配一块内存。我可以简单地将分配作为锯齿状数组进行,但执行连续块更有效。
这是我当前的代码片段:
//Creating an array of proper size
//I first create an array of pointers
phi = new double**[xlength];
//I then create another array of pointers
phi[0] = new double*[xlength*ylength];
//At this point, I assume phi[0] and phi[0][0] have the same location. Is this not true?
phi[0][0] = new double[xlength*ylength*tlength];
//Now, I allocate the big block of data that will actually store my data
//I assume phi[0][0][0] has the same location as phi[0][0]. Is this right?
//Now, I'm trying to setup the pointers to match up in the single block of memory
for (int i=0;i<xlength;i++)
{
for (int j=0;j<ylength;j++)
{
phi[i][j] = phi[0][0] + tlength*ylength*i + tlength*j;
}
}
//Does this not work? It feels as though it SHOULD
添加回工作代码,因为答案取决于工作代码
double*** A = new double**[m];
double** B = new double*[m*n];
double* C = new double[m*n*o];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
B[n*i+j] = C + (n*i+j)*o;
}
A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
for (int k=0; k<o; k++) {
A[i][j][k] = <my_value>;
}
}
这是解决方案的家伙!
不要做3D矩阵,哈哈!这是我有史以来最不受欢迎的帖子!
做一个 1D 矩阵并按照这个链接上的答案C++ Segmentation Fault AfterWhen Try to Write to Matrix
这是该链接的重要部分:
但是你不能使用 phi[i][j][k] 符号,所以你应该
#define inphi(I,J,K) phi[(I)*xlength*ylength+(J)*xlength+(K)]
和写inphi(i,j,k) instead of phi[i][j][k]