I can only expand by 1 (and this is strange by the way) Name: add:

class double_Digit { double digit; int size; double *ar; public: double_Digit() :size(NULL), ar(nullptr) { } double_Digit(int _size) :size(_size), ar(nullptr) { if (size > 0) { ar = new double[size]; } } ~double_Digit() { if (ar) { delete[]ar; } } double* add(int sizetmp) { double* arr = new double[sizetmp]; for (int i = 0; i < size; i++) { *(arr + i) = *(ar + i); } delete[]ar; double* ar = new double[sizetmp]; for (int i = 0; i < size; i++) { *(ar + i) = *(arr + i); } delete[]arr; size++; return ar; } double* GetArray() const { return ar; } int GetSize() const { return size; } }; 
  • The essence of the question is not clear. - Vlad from Moscow
  • @VladfromMoscow, everything seems to be clear. - Qwertiy

2 answers 2

You have a meaningless Add method, since you are trying to copy uninitialized arrays in it. At best, in the constructors, you dynamically allocated memory to the array, but you did not initialize it with anything. Either you should change the constructors so that they initialize the array when it is created, or so that the class supports the number of actual elements in the array.

Then it is not at all clear why the sign integer type is used for the size of the array. It would be correct to use the size_t type in order not to check the corresponding value whether it is negative or not.

If we assume that the array is somehow initialized, then the Add function might look like this

 double * add( size_t new_size ) { if ( new_size != this->size ) { double *tmp = new double[new_size](); size_t n = std::min( this->size, new_size ); for ( size_t i = 0; i < n; i++ ) tmp[i] = this->ar[i]; delete [] this->ar; this->ar = tmp; this->size = new_size; } return this->ar; } 

    It is not clear why you make two copies? Select a new array, copy the data into it, and then simply assign pointers.

    But the main thing - I just can not understand why you increase the size value like this:

      delete[]arr; size++; // ?????? return ar; 

    This is, in fact, the answer to your question - why the size increases by 1. It then increases as it should, but you yourself increase the variable only by one .