【问题标题】:Dynamic Allocation using a member in a structure使用结构中的成员进行动态分配
【发布时间】:2017-02-04 12:09:18
【问题描述】:

我尝试为结构成员分配内存: 这是结构:

struct conserved_variables {
    double **roh;
    double **mx;
    double **my;
    double **E;
}; 

我构造了这个结构的数组

conserved_variables ** U= new conserved_variables*[Ny];
for (int i = 0; i < Ny; i++)
{
    U[i] = new conserved_variables[Nx];
}

然后我尝试为这个结构中的每个成员分配数组:

for (int i = 0; i < Ny; i++)
        for (int j = 0; j < Nx; j++)
        {
            U[i][j].E = new double*[Order + 1];
            U[i][j].mx = new double*[Order + 1];
            U[i][j].my = new double*[Order + 1];
            U[i][j].roh = new double*[Order + 1];
            for (int k = 0; k <= Order; i++)
            {
                U[i][j].roh[k] = new double[Order + 1];
                U[i][j].mx[k] = new double[Order + 1];
                U[i][j].my[k] = new double[Order + 1];
                U[i][j].E[k] = new double[Order + 1];
            }
        }

我收到此错误消息:

    Exception thrown at 0x01153FDD in FR_1D_Advection_Equation.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.

If there is a handler for this exception, the program may be safely continued.

【问题讨论】:

  • 也许如果你使用std::vector,你就不必仔细跟踪你的内存分配,即使是一个小错误也会在你的脸上炸开。
  • Yikes,所以一个指向指针结构数组的指针?看起来很复杂,变量名没有给出任何线索——你想用这个解决什么问题?某种多维矩阵?

标签: c++ struct dynamic-allocation


【解决方案1】:

这是内存局部性的噩梦。

至于你的实际错误,你没有小心你的内部循环:

for (int k = 0; k <= Order; i++)
//                          ^
//                          you mean k

这是爆炸性的,因为您不小心将i 推到了U 数组的边界之外。如果您使用调试器花费的时间与您在 Stack Overflow 上提问的时间一样多,那么应该很容易发现。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2016-04-10
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2022-11-07
    • 2012-11-03
    • 2016-01-18
    • 2012-12-26
    相关资源
    最近更新 更多