I defined a function to calculate the distance between 2 points in 2D, these points being arrays of 2 elements. My "distance" function gives me different results when passing the arrays as constant, or not, in the function.
Here is my code:
#include <iostream>
#include<math.h>
using namespace std;
double distance(const double *x1,const double *x2)
{
double dist;
dist=sqrt((x1[0]-x2[0])*(x1[0]-x2[0]) + (x1[1]-x2[1])*(x1[1]-x2[1]));
return dist;
}
double distance1(double *x1,double *x2)
{
double dist;
dist=sqrt((x1[0]-x2[0])*(x1[0]-x2[0]) + (x1[1]-x2[1])*(x1[1]-x2[1]));
return dist;
}
int main() {
double x1[2],x2[2];
double val;
x1[0]=1;x1[1]=0;
x2[0]=0;x2[1]=1;
val=distance(x1,x2);
cout << val << endl;
val=distance1(x1,x2);
cout << val << endl;
return 0;
}
Doing so I get :
-2
1.41421
I don't understand why the "distance" function does not do the same as "distance1". I would expect the same result but "distance" preventing me from modifying the content of the x1 and x2 arrays.
Also, when naming both function "distance", I get the expected results (1.41421), which function is then called in that case ?
Any help would be appreciated.