1

I've tried to make an algorithm, which counts how many numbers are divided without a remainder. Code works, but every time I run it, I'm getting "trash" numbers in my output. I'm using dynamic arrays to solve a problem.

#include <iostream>
using namespace std;

 int main() 
 {
    int N = 30;

    int *data = new int [N];

    for (int i = 0; i < 100; i++)
    {
        for (int c = 1; c < N; c++)
        {
            if (i % c == 0)
            {
                data[c] += 1;
             }
         }
     }

     for (int k = 1; k < N; k++)
     {
        cout << data[k] << endl;
     }

     delete [] data;
 }

I've expected to have, at least, what C++ Shell says: http://cpp.sh/6xtc

100
50
34
25
20
17
15
13
12
10
10
9
8
8
7
7
6
6
6
5
5
5
5
5
4
4
4
4
4

, but got in different IDE the same result:

100
11932994
34
25
20
17
15
13
12
620757039
37045
11951945
8
11927896
7
7
7290
158
6
5
5
570425383
37040
11951941
4
11927892
4
1835102827
859059803
Pr.Germux
  • 55
  • 5
  • 1
    *Code works, but every time I run it, I'm getting "trash" numbers in my output.* This sentences consists of two irreconcilable parts. – SergeyA Jul 11 '19 at 19:50

2 Answers2

6

You do

int *data = new int [N];

And allocate an N-sized array. Then you immediately start trying to increment the values in it:

data[c] += 1;

But what was in there to begin with?

If you want to guarantee that all the values will be initialized to 0, per this answer you can allocate your array with:

int *data = new int [N]();
//                    ^^^^

<Obligatory "you should just be using std::vector!" comment here.\>

(But actually though, vectors would make this way easier and avoid this issue entirely)

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • I'm thinking of a use of "trash information" which I initialized to 0. Could it be used somewhere else in other important running programs on computer and I've just interrupted a process? – Pr.Germux Jul 11 '19 at 20:03
  • 1
    @Pr.Germux I'm not entirely sure I understand your question here, but when you do `new int [N]();` you're saying "Please give me enough consecutive blocks of memory to store N ints" and the computer goes and finds a chunk of memory that big that no one else is using and puts a sticky-note with your name on it there :) – scohe001 Jul 11 '19 at 20:07
3
data[c] += 1;

You add something to an uninitialized value. data[c] was not necessarily 0 before that. new does not initialize a dynamic array to zero.

Quit all new/delete and use std::vector<>. And, do learn to use the debugger - really helpful in this case.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78