0

Hi,

I'm pretty new to C++ but have a lot of experience in Python. In python its pretty straight forward to make functions that both take arrays/vectors as input and return arrays/vectors.

My thought here is to make a function to calculate the gravitational force between to bodies with mass m1 and m2, at position r1 and r2 respectively. r1 and r2 should be arrays (mathematical vectors) and the resulting force should also be an array (mathematical vector).

```
using namespace std;
#include <iostream>
double *grav_force (double m1, double m2, double *r1, double *r2){
// Calculate distance between bodies:
double r12; // scalar distance
double r_12 [2]; // distance vector
for (int i=0; i<2 ; i++){
r12 += (r2[i] - r1[i])*(r2[i] - r1[i]);
r_12[i] = r2[i] - r1[i];
}
r12 = sqrt(r12);
// Gravitational factor:
double G = m1*m2/(r12*r12*r12); // Grav.const. = 1
double f_x = G*r_12[0]; // r_12[0] is the x-coordinate of the distance vector
double f_y = G*r_12[1];
double f_g [2];
f_g[0] = f_x;
f_g[1] = f_y;
return f_g;
}
int main(int argc, char* argv[])
{
double r1 [2] = {1.0, 2.0};
double r2 [2] = {2.0, 4.0};
double m1 = 1.0;
double m2 = 1.0;
double *asd = grav_force(m1, m2, r1, r2);
cout << "*asd: " << *asd << endl;
return 0;
}
```

Output:

`*asd: 0.0894427`

As you can see only the first component of the force vector is returned. How to solve this?

*Edited 5 Years Ago by brynjar*: typo