user5905971
user5905971

Reputation:

Issue processing an array created with new operator

I am fairly new to the concepts of new, delete, and pointers, so perhaps the solution is obvious to people reading this, but I am honestly perplexed.

I am supposed to have an array which is initialized at 2 elements, but as the user enters more numbers, it would constantly expand by 2 elements using the new operator until the user enters "-1".

While I have coding to allow the array to grow, the results are disappointing when the program then processes the array to return the difference between the smallest number in the array, and each of the other numbers. The only hint I was given was: "When you change the capacity, you don’t copy from the original array to the new one.", however, I am not sure what to make of that.

A nudge in the right direction would be greatly appreciated.

#include <iostream>

using namespace std;

int main(){

int *ptr;   //pointer to array
int capacity = 2;   //capactity of array
int size = 0;       //how many ints recorded in array
ptr = new int[capacity];
int tmp = 0;

int *numArray = new int[capacity];

while (true){
    cout << "Enter a number: ";
    int num;
    cin >> num;
    if (num == -1) break;
    if (size == capacity){
        int *temp = new int[capacity + 2];
        capacity += 2;
        delete[]ptr;
        ptr = temp;
    }
    ptr[size++] = num;
}

int smallest = numArray[0];

// Code to process array and look for smallest number
for (int i = 0; i < capacity; i++){
    if (numArray[i] < smallest){
        smallest = numArray[i];
    }
}

cout << endl << "The smallest number in the array is: " << smallest << endl << endl;

for (int i = 0; i < capacity; i++){
    int difference = numArray[i] - smallest;
    cout << "The difference between " << numArray[i] << " and the smallest number in the array is : " << difference << endl;
}

system("pause");
}

Upvotes: 2

Views: 44

Answers (1)

Ed Heal
Ed Heal

Reputation: 60017

In this bit of code

if (size == capacity){
    int *temp = new int[capacity + 2];
    capacity += 2;
    delete[]ptr;
    ptr = temp;
}

You create a new array but do not copy the existing arrays contents into it.

Add the following line just after creating the array

for (int i = 0; i < capacity ; ++i) temp[i] = ptr[i];

When coming to do the calculations you will have the entered values in the array.

Alternatively look into std::vector

Upvotes: 2

Related Questions