I've written a program that works for most input, but if I ask it to make a increase precision by using a larger array (about 320x320 was when I started seeing trouble) it crashes. I searched for my issue online and found this similar problem and this tutorial on what to do about it. The problematic part of my original code is below - I had precision=320 and holepop=770.
double spacing = 2.0/(precision+1);
int lattice_int[precision][precision];
for (i=0; i<precision; ++i){
for (ii=0; ii<precision; ++ii){
mindist_sq = 2.0;
lattice_int[i][ii] = 0;
for (iii=0; iii<holepop; ++iii){
xdist = abs(xcoord[iii] + 1.0 - spacing/2 - spacing*i);
ydist = abs(ycoord[iii] - 1.0 + spacing/2 + spacing*ii);
thisdist_sq = xdist*xdist+ydist*ydist;
if (thisdist_sq < mindist_sq){
lattice_int[i][ii] = dint[iii];
mindist_sq = thisdist_sq;
}
}
}
}
I tried to fix it with this change in the first two lines:
int * lattice_int;
double spacing = 2.0/(precision+1);
lattice_int = new int[precision][precision];
(I also put in "delete lattice_int[][];" at the end.) However, I received this error: 'precision' cannot occur in a constant expression Is it because I'm trying to work with multiple indices? What can I do to work around my problem? Thank you!
Don't use
new[]
, it'll only cause you pain, suffering, memory leaks, use-after-frees, etc.You can use
std::vector
in this respect.No memory freeing necessary.