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;
}

      

+3


source to share


5 answers


Change output[n]

to output[i]

instead, you are not writing any indexes to the array as it is output[7]

out of bounds. i

is your cycle counter, notn



+9


source


change

output[n] = sum;

      



to

output[i] = sum;

      

+4


source


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, " "));

      

+4


source


output[n] = sum;

, n

7

goes out of bounds output

and you write data every time. Note that this is undefined behavior as well. You are accessing float value = input[i];

right in the for loop, so I assume this is just a typo.

Update

output[n] = sum;

      

to

output[i] = sum;

      

+3


source


Replace 'n' with 'i' for your iteration in PrefixSum;)

+2


source







All Articles