### 2d Array Troubles

Hi,

I am trying to do a time evolution of a pressure wave in 2 dimensions for a computational physics class. Well, I have to define a 2d array for all the grid points I believe. Well, the best way I can think of to do this is by definining

double * grid;

outside any method with all my other variables and then

grid = new double[sizeX][sizeY];

in my init function where I initilize all my arrays and glut and whatnot.

Unfortunately, xcode is throwing me the following error for that declaration:
"error: cannot convert 'double (*)[128]' to 'double*' in assignment.

Later in the code with the code
 ``12`` `````` grid[x][y] = exp(-1 * ( pow((x-xcenter),2)/(2*sigmaXY*sigmaXY) + pow((y-ycenter),2)/(2*sigmaXY*sigmaXY))); P = grid[x][y];``````

I get the errors "error: invalid types 'double[int[' for arrays subscript' for both. I found hat if I use the declaration double ** grid; it gets rid of those two errors but not the first one.

I'm sure its just an error that I haven't picked up but any help would be very much appreciated.

Further info: I am on an intel mac using xcode and the intel c++ compiler version 11.0.
 ``12345678910111213`` ``````// To Allocate double **grid; grid = new double*[sizeX]; for (int i = 0; i < sizeX; ++i) grid[i] = new double[sizeY]; // To Use grid[x][y] = 0.0; // To Clean Up for (int i = 0; i < sizeX; ++i) delete [] grid[i]; delete [] grid;``````

Edit: You may find using a vector of vectors a better approach, less memory management you have to do yourself.
Last edited on

What would be the advantage to using a vector of vectors? What memory management is taken care of with that approach? Can my code still simply use grid[x][y]?
It will free you from having to allocate, resize, and free the dynamic memory. And yes, vectors do allow you to use the [] operators, but I recommend the at() member function since it will throw an exception if you access memory out of bounds.
in c++ call:
double **grid;
grid=new double*grid[x];
for(int i=0;i<y;i++)grid=new double[y];
that is the vector of the vectors. We can call 3 4 d array by that way.
in c can call:
double grid[x][y];
grid=malloc(sizeof(x*y));
but in the momery it take X*Y+1 place on it. 1 for the rood which take the ip for the headot the 2d ray.
that right????????????????????
@roodtree: incorrect.

Vector of Vectors.
 ``123456789101112131415161718192021222324`` ``````#include #include using namespace std; int main() { int sizeX = 10; int sizeY = 10; vector > grid; // Resize our Grid grid.resize(sizeX); for (int i = 0; i < sizeX; ++i) grid[i].resize(sizeY); grid[0][0] = 3.0; grid[5][5] = 4.5; cout << "0/0 = " << grid[0][0] << endl; cout << "5/5 = " << grid[5][5] << endl; return 0; }``````
Topic archived. No new replies allowed.