我是c ++的新手,对于我的程序,我想为结构分配一个2d数组指针。代码是
struct normal
{
double n_x, n_y;
};
这是我定义的结构,我想在main中分配一个2d数组指针,如下所示:
normal **normal_cell;
*normal_cell = new normal[p];
for(int i=0;i<p;i++)
{
normal_cell[i] = new normal[4];
}
这个2d指针应该传递给一个函数。当我尝试这样做时,我的程序没有运行。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:3)
只需使用normal_cell = new normal*[p]
代替*normal_cell = new normal[p]
答案 1 :(得分:2)
在C ++中,我们使用向量而不是数组和指针:
#include<vector>
using std:: vector;
struct normal
{
double n_x, n_y;
};
vector<vector<normal>> normal_cell;
void foo() {
int p=10;
normal_cell.resize(p);
for(int i=0;i<p;i++)
{
normal_cell.at(i).resize(4);
}
}
答案 2 :(得分:1)
试一试:
//if normal_cell[4][5]
const int m = 4; //row
const int n = 5; //column
normal **normal_cell = new normal*[m]; //new row
for(int i=0; i<m; ++i)
normal_cell[i] = new normal[n]; //new column