0

Could someone explain to me why this for-loop only runs one time no matter what n is:

double CalcDist(unsigned int n, Point p, Point* s)
{
    double sd[n];
    for(int i = 0; i < n; i++)
    {
        sd[i] = s[i].Dist_To(p);
        return sd[i];
    }
}

Thanks in advance for any help.

xtrap
  • 21
  • 2

2 Answers2

8

return exits the function prematurely, and is within the body of the for loop.

Also, be very careful when mixing unsigned and signed types when using expressions like i < n. Do you know off hand what would happen if n was 0?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Thanks for the reply. And no, I don't know off hand. I was using unsigned because in my case n should never be negative and I wanted to extend the range in the positive direction. My understanding is quite rudimentary. – xtrap Feb 02 '17 at 11:43
  • I want to return the values from this into an array. If I can't use `return`, without ending my loop prematurely, how do I go about doing this? – xtrap Feb 02 '17 at 12:03
  • The equivalent to `s` is modified in the caller. There's no need to explicitly return anything. – Bathsheba Feb 02 '17 at 12:05
  • if you want to return an array of values then declare the function to return a pointer to datatype; in your case `double*` as you can see in the answer of @Steranoid. – Raindrop7 Feb 02 '17 at 12:20
  • If you want to leave `s` as it is, I'd rather see a `std::vector` as the return type. Modern compilers can all obviate the value copy using NRVO. – Bathsheba Feb 02 '17 at 12:23
1

If your aim is to determine the distance between one point to each point in an array, it goes like this :

double * CalcDist(unsigned int n, Point p, Point* pointsArray) {
    double * result = new double[n]; //Iso C++ forbids veriable length array
                                     //so don't use result[i] but this instead
    for (unsigned int i = 0; i < n; i++) { //set i as an unsigned int as n is one
        result[i] = pointsArray[i].Dist_To(p);
    }

    return result;
}
Steranoid
  • 30
  • 3
  • Thanks for the help. Now, how do I access that array outside of this function? Let's say I want to sort the array elsewhere. – xtrap Feb 02 '17 at 12:49
  • The return gives you the adress of the array so you can access it when you catch the return : double * foo = CalcDist(8, p, array); //do something with foo Don't forget to delete it after with delete[] result; – Steranoid Feb 02 '17 at 13:23
  • To be really safe, you should also use a shared_ptr so if you don't use the result and/or forgot about the delete you don't have any memory leaks. – Steranoid Feb 02 '17 at 14:05