P
P
Pavel2015-11-12 09:50:43
C++ / C#
Pavel, 2015-11-12 09:50:43

How to increase the size of an array in C++?

Please give me an approximate idea of ​​how to increase the size of an array in c++.
The task is such that there is a dynamic array that the user fills in. Next, you need to write a function that adds an element to the array only if this element is missing. I wrote this function:

int* addItemToArray(int* array, int size, int newItem){
  for (int i = 0; i < size; i++){
    if (newItem == *(array + i)){
      return nullptr;
    }
  }
  int* newArray = new int[size + 1];
  for (int i = 0; i < size; i++){
    *(newArray+i) == *(array + i);
  }
  *(newArray + size + 1) = newItem;
  return newArray;
}

It returns the address of a new array, then I try to accept this result:
int L,I;
    cout << "Input size of array:";
    cin >> L;
    int* lineArray = new int[L];
    srand(time(0));
    for (int j = 0; j < L; j++){
      cout << "Type number to fill array:";
      cin >> I;
    }
    cout << "Type number to add to array:";
    cin >> I;
    while ((lineArray = addItemToArray(lineArray, sizeof(lineArray) / sizeof(lineArray[0]), 4)) == nullptr){
      cout << "Number is already in array!Type another:";
      cin >> I;
    }

But it returns a zero address to me. As far as I understand, this is due to the fact that the lifetime of my new array ends at the exit of the function ... How can I overcome this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Adamos, 2015-11-12
@rusbaron

1. You are confusing yourself by using *(array + i) instead of array[i]
2. You are creating a new array without deleting the old one. It is clear that in the laboratory this is not critical. But if you are going to live with C ++, then either such things will hurt your eyes, or learn another language.
3. You have a function that is passed an array and an element. The function returns either a new array or nullptr. This is unnatural. The function must return a reference to the array - and whether it is new or old can be decided outside the function. It seems unimportant, but good code is based on such trifles, and shit code grows precisely because "everything is clear here anyway."
4. Finally, in the trash program. Values ​​are requested for the array, but they are not entered into the array itself. It is not the entered value that is added to the array, but 4 (?). lineArray is immediately lost as nullptr is assigned to it...

K
Konstantin, 2015-11-12
@Drakonn

also pass a new array as a pointer, it will be filled in the method and then use it)

V
Vitaly, 2015-11-12
@vt4a2h Куратор тега C++

Я бы вам посоветовал посмотреть программу в оталдчике и понять что не так. Это действительно полезно для обучения. + поймёте что у вас неправильно.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question