Hi there, I'm fairly new to this C++ thing so I hope you can help.
I'm writing a program that prints out the coordinates of atoms in a simulation box (30x30x30). I have a fair few header and .cpp files so I'll only paste the bits that are faulty. I basically set up a subroutine to print out the coordinates of the atoms, and then use a loop and a random number generator to "insert" particles into that box. Here's the code:
// Subroutine to print a PDB of the coordinates
void print_pdb(double **coords, const int simbox_TotalNparticles, const int move)
{
char filename[128];
sprintf_s(filename, 128, "output%000006d.pdb", move);
FILE *f = fopen(filename, "w");
fprintf(f, "CRYST1 %8.3f %8.3f %8.3f 90.00 90.00 90.00\n",
sim_box[0], sim_box[1], sim_box[2]);
for (int i = 0; i < simbox_TotalNparticles; i = i + 1)
{
fprintf(f, "ATOM %5d Methane Methane 1 %8.3f%8.3f%8.3f 1.00 0.00 Methane\n",
i+1, coords[i][0], coords[i][1], coords[i][2]);
fprintf(f, "TER\n");
}
fclose(f);
}
int main()
{
// Random variables and other
double **coords = new double*[simbox_TotalNparticles];
int seedmain;
// Random seed
srand ( (unsigned int)time(NULL) );
seedmain=1; //time(NULL);
// Starts the seqeunce of randon numbers
CRandomMersenne RanGen(seedmain);
CRandomMersenne *pRanGen;
pRanGen=&RanGen;
double random=RanGen.Random();
// Randomly generate the coordinates of the atoms in the box
for (int i = 0; i < simbox_TotalNparticles ; i = i + 1)
{
coords[i] = new double[3];
// Note "random(0,x)" would generate a random number
// between 0 and $x
coords[i][0] = random*sim_box[0];
coords[i][1] = random*sim_box[1];
coords[i][2] = random*sim_box[2];
// Print the initial PDB file
print_pdb(coords, simbox_TotalNparticles, 0);
cin.ignore();
}
return (0);
}
It should be pointed out that the problem lies with the print_pdb function. The other variables you see there are defined in other files. When I debug the program I get the following message:
"Unhandled exception at 0x775415de in new.exe: 0xC0000005: Access violation reading location 0xcdcdcddd."
It should be noted that if I comment out the final "// Print the initial PDB file" part at the end the program runs successfully.
Any ideas?
Cheers