I'm trying to make a array that will auto fill with random numbers when the user tells the program how many numbers are to be in the array. I don't see any issues with it.
If you want to make an array which is unknown in size to the compiler at run time then you have to use a pointer to that array, and allocate the memory manually yourself like in the code below:
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <new>
#include <exception>
usingnamespace std;
int main()
{
srand(time(NULL)); /* You need to set up a random generator in order to use random numbers */
int numberOfInts = 0;
int* myArr;
cout << "Number of integers you want to use?\n:";
cin >> numberOfInts;
try{
myArr = newint[ numberOfInts ];
}catch(exception){
cerr<<"OH NO! An error occurred allocating the memory for this array!";
return 0;
}
for(int i = 0; i < numberOfInts; i++)
{
myArr[ i+1 ] = rand()%100 +1; /* <---- generates a random number form 1 to 100 */
}
while(numberOfInts > 0)
{
cout << myArr[ numberOfInts ] << " ";
numberOfInts--;
}
delete myArr; // must delete allocated pointer!
delete[] myArr; // must delete contents of created array!
return 0;
}
I assume the OP is using GCC, which allows you to use C99 style variable length arrays... What you suggests is, of course, proper C++. Though you should delete arrays like delete [] myArr;
Also, having caught the error, you're allowing the code to still run?
The exception handling was designed to be an example not an actual finished product, and as for the deletion error I've been programming with Java for quite some time and need to shake off the rust in C++, but I see what your getting at, thanks.