Answer the question
In order to leave comments, you need to log in
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;
}
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;
}
Answer the question
In order to leave comments, you need to log in
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...
also pass a new array as a pointer, it will be filled in the method and then use it)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question