M
M
matveyvarg2016-12-11 15:37:37
C++ / C#
matveyvarg, 2016-12-11 15:37:37

How to populate a dynamically created array?

There is a class that has an attribute. int *koefs ;Next, this array is initialized in the constructor as:

this->koefs = new int[fn + 1]; //fn - передается в конструктор ( с этим все ок)

And filled in:
for (i = 0; i <= fn ; i++)
  {	
    //srand(time(NULL));
    this->koefs[i] = random_at_most(99) 
    
  }

random_at_most is a function that returns a random value. Also works correctly.
As a result, there is only 1 element in the array.
Found that c++ only stores a pointer. But how then to fill the elements of the array?
If possible, I would like not to use vectors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-12-11
@Mercury13

There is not even a toy code, and you can’t say for sure. I see three possible reasons.
1. Either the copy constructor or assignment operations are not registered (and everything is in order with the destructor). The pointers keep accessing the freed memory, and by some lucky coincidence, the first element matches.
2. Or a name conflict: fn is a constructor parameter and fn is an internal field.
3. You have a commented out here srand(time(NULL));. I don’t know what is in the random_at_most function, but if there is srand, move it to another place. The processor runs a million times faster than the timer. “You want it to be random,” but there will be repetitions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question