Dynamic Array Initialization

Hi,

I believe I'm having an error with initializing my dynamic array -data-.
I'm not 100%, but the sum value comes out to be 0 when the program is run, and it's my best guess. However, I've tried initializing it in a bazillion ways and nothing changes. Is it even an initializing problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

int main(){
    
    int items;
    long long int sum = 0;

    cout << "How many items should be summed? ";
    cin >> items;

    int* data = new int[items]{};

high_resolution_clock::time_point t1 = high_resolution_clock::now();

    for(int i = 0; i < items; i++){

    sum += data[i];

    }

high_resolution_clock::time_point t2 = high_resolution_clock::now();

    long long int duration = duration_cast<microseconds>(t2 - t1).count();

    cout << "sum: " << sum << endl;
    cout << "duration: " << duration << endl;

return 0;

}


Thank you.
Last edited on
> sum value comes out to be 0
┬┐what should it be?

> I've tried initializing it in a bazillion ways
I only see one
ne555,

-It should be the accumulation of all array elements-
is what I was going to say.

But I just realized that -items- only sets the size of the array. It doesn't actually store anything in array. So initializing it the way I did is setting everything to zero isn't it? Then it's adding up a bunch of zeroes.

My bad yall.
to clarify
new int[items]{} initialise all the elements to 0
new int[items] (note the lack of braces) doesn't initialise the elements, they have whatever value was at that memory address.
Registered users can post here. Sign in or register to post.