Reputation: 21
I am trying to create a program which would fill up an array that is initialized at 2 elemental values, but lets the user keep on entering numbers. As the user enters more values, the program is supposed to create a new array with 2 more element holders, transfer the numbers from the initial array to the new one, and delete the old one.
Once the user inputs -1, the program is supposed to do other stuff with the array, which I know how to do, but since the input is not stopping when I enter -1, I just didn't bother with that part yet.
To be honest though, I have no idea what I am doing here since I am new to the concepts of new and delete. I do have some code, but only because I was given hints.
If it was up to me, I probably would have tried to do this with vectors.
Any hints 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];
for (int i = 0;; i++) {
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 = tmp;
}
ptr[size == capacity] = num;
}
}
}
Upvotes: 1
Views: 46
Reputation: 63481
You are close. But there are several issues.
ditch the for
loop. Otherwise when you break
from the while
loop, it just enters again forever.
You need to increment size
, otherwise size == capacity
will never be true.
You forgot to actually copy the values in when resizing the array.
Incorrect assignment *ptr = temp
should be ptr = temp
.
Bogus array assignment using boolean index ptr[size == capacity] = num
. Perhaps combine this with (2) and do ptr[size++] = num
.
All this together:
while (true)
{
cout << "Enter a number: ";
int num;
cin >> num;
if (num == -1) break;
if (size == capacity){
int *temp = new int[capacity + 2];
for( int i = 0; i < capacity; i++ ) temp[i] = ptr[i];
capacity += 2;
delete[]ptr;
ptr = tmp;
}
ptr[size++] = num;
}
Upvotes: 2
Reputation: 91
First, would recommend you using char array. You can use memcpy for this. Below code assume you read one int at a time.
int *temp = new int[capacity + 2];
memcpy ( tmp, ptr, capacity );
temp[capacity + 1] = num;
capacity += 2;
Upvotes: 0