I'm super duper new to coding and I'm just learning this as a hobby. I'm following a course and this is the code I wrote (user input to a dynamically created array):
#include <iostream>
using namespace std;
int main()
{
int capacity = 5;
int* numbers = new int[capacity];
int index=0;
while (true)
{
cout << "Please enter a whole number. ";
cin >> numbers[index];
if (cin.fail())
{
cout << "That's not a whole number, ya dingus. Here's all yer numbers so far:" << endl;
break;
}
index++;
if (index == capacity)
{
int* morenumbers = new int[2*capacity];
for (int j = 0; j < index;j++)
{
morenumbers[j] = numbers[j];
}
delete[] numbers;
numbers = morenumbers;
}
}
for (int i = 0; i < index;i++)
cout << numbers[i] << endl;
delete[] numbers;
return 0;
}
My questions are:
I set the initial size of the array to 5 and it can be increased to 10. Why the heck does it work for 20 numbers as well?
The variable
indexthat I declared changes in thewhileloop. So, if I'm not wrong, its scope is within thewhileloop, right? Then, why is it that I can use it outside of thewhileloop (as for example my lastforloop that prints out all the entered numbers)?
My main focus right now is not writing efficient code, but learning what the commands do, so despite the code apparently working flawlessly, I want to know why it works.
new[]so early on in your C++ coding endeavors? A modern C++ course would be teaching uses ofstd::vector, asnew[]is not a beginner topic, and frankly, shouldn't be used if the goal is to have a dynamic array.new[], you have no guarantees as to what happens when you stomp on memory that you didn't allocate. My main focus right now is not writing efficient code -- it isn't about efficient code -- it's about writing code that is easier to debug, easier to follow and easier to maintain.