Hi there, I'm fairly new to C++ and I'm attempting to learn how to use pointers. I have the following file that creates coordinates and then moves them in random directions using a random number generator.
The value sigmaf_point is inputted from a text file:
void methane_coords(int &atom_types, double *&sigmaf_point, double *&epsilonf_point, double *&massf_point, int &atom_number, double *&x_point, double *&y_point, double *&z_point, int *&type_point)
<code> double dummy_int = 1;
string dummystring;
string s;
ifstream Dfile;
std::stringstream out;
out << 1;
s = out.str() + ".TXT";
Dfile.open (s.c_str());
if (Dfile.fail())
{
return;
}
for (int i=0; i<dummy_int; i++)
{
Dfile >> sigmaf_point[i];
}
Which I then use in another function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
double initial_energy(double **coords_fluid, double **coords_solid, int n_atoms, constdouble *box_size){
// Loop over all pairs of atoms and calculate the LJ energy
double total_energy = 0;
for (int i = 0; i <= n_atoms-1; i++)
{
sf1=sigmaf_point(coords_fluid[i][3]);
ef1=epsilonf_point(coords_fluid[i][3]);
// Energy fluid-fluid
for (int j = i+1; j <= n_atoms-1; j++)
{...
}
coords_fluid is created in the main file like so:
1 2 3 4 5
double **coords_fluid = newdouble*[5000];
for (int i = 0; i < n_atoms_methane; i++)
{
coords_fluid[i] = newdouble[4];
}
Now the problem is with `sf1=sigmaf_point(coords_fluid[i][3]);
I get the error "expression must have pointer to function type" for sigmaf_point. I'm a bit confused about this, I know it's about how I call the variable but can't seem to fix it.
First, you should avoid using "pointer" too much!!! (especially in this situation - say honestly that's insane) In general it's extremely dangerous. I recommend you use the vectors instead.
Second :
What definition type of "sigmaf_point"? Function, variable, or anything else?
So what is the advantage of vectors/disadvantages of pointers. My initial impressions of them is that they are - like you say - a bit dangerous. But seeing as my C++ ability is fairly new and the programs that I need to write require me to call variables that have large amounts of data I assumed that pointers would be the best.
The problem that I've found is that when I call a function that has a loop in it and it's dealing with an array of values, if I don't use pointers then the value that gets returned is simply the value returned by the last iteration of the loop, not every iteration of the loop. Pointers seemed to fix this.