Array / pointer confusion
Why is the following code printing "0 0 0 0 0 0 0 "
? I expected "1 3 6 10 15 21 28 "
.
#include <iostream>
using namespace std;
void PrefixSum(float * input, float * output, int n){
float sum = 0;
for (int i=0;i<n;i++){
float value = input[i];
sum += value;
output[n] = sum;
}
}
int main(int argc, const char * argv[])
{
float input[] = {1,2,3,4,5,6,7};
float output[] = {0,0,0,0,0,0,0};
PrefixSum(input, output, 7);
for (int i=0;i<7;i++){
cout << output[i] << " ";
}
return 0;
}
source to share
As everyone pointed out, you are using n
as an index instead i
, so you never change any value in the array.
Writing loops are error prone, many of us will be wrong over the years. Better to reuse existing code.
You are calculating partial_sum
. Using the standard library, you can write it like this:
#include <iostream>
#include <numeric>
int main(int argc, const char * argv[])
{
using std::partial_sum;
using std::cout;
const int SIZE = 7;
float input[SIZE] = {1,2,3,4,5,6,7};
float output[SIZE] = {0,0,0,0,0,0,0};
partial_sum(input, input+SIZE, output);
for (int i=0;i<SIZE;i++){
cout << output[i] << " ";
}
return 0;
}
We can also eliminate the loop that prints out the result:
#include <algorithm>
#include <iterator>
//...
using std::copy;
using std::ostream_iterator;
copy(output, output+SIZE,
ostream_iterator<float>(cout, " "));
Finally, if you don't want an array of intermediate results, we can simply cast the results directly to ostream
:
partial_sum(input, input+SIZE,
ostream_iterator<float>(cout, " "));
source to share