Tuesday, July 28, 2009

C++ question?

i want to write the following c++ function





double sum (double * begin,double*end)


//pre:begin points to the first element of one dimensional array


//end points to the entry after the last element of the array





//post:return sum of all the entries of the array

C++ question?
why not pass the array as a parameter into the function?





e.g.


void main() {


double myarray[] = {2.1, 4.5, 6.4, 8.2, 10.1};


cout %26lt;%26lt; sum(myarray,5);


}





double sum (double arg[], int length) {


double result = 0;


for (int n=0; n%26lt;length; n++) {


result = result + arg[n];


}


return result;


}
Reply:You were probably given the function signature in the problem statement, but I think it should look like this:





double sum(const double * const, const double * const);





So the pointers given to sum are const, pointing to const data. This is particularly important for the end pointer, which points past the end of the array, where sum should not be allowed to write. The caller probably shouldn't be writing to *end either. In general, if you're dealing with pointers outside the bounds of declared arrays or structs, or allocated memory, you have to be careful or bad things can happen.





There's not much to the function. Just start at the beginning, work to the end, and accumulate the sum as you go:





double sum(const double * const begin, const double * const end) {


const double *p = begin;


double result = 0;


while (p != end) {


result += *p++;


}


return result;


}





const double *p is a non-const pointer, referencing const data.





In the statement: result += *p++


the double pointed to by p is added to result, then the pointer p is incremented to point to the location of the next double.

nobile

No comments:

Post a Comment