Why isn't this printing anything?

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
    int numberOfInts = 0;

    cout << "Number of integers you want to use?\n:";
    cin >> numberOfInts;

    int myArr[ numberOfInts ];

    for( int i = 0; numberOfInts < i; i++ )
    {
        myArr[ i ] = rand() % 100;
    }

    for( int n = 0; numberOfInts < n; n++ )
    {
        cout << myArr[ n ] << " ";
    }
}
Apart from using < where you mean > ???

Andy
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <new>
#include <exception>
using namespace 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 = new int[ 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;
}


Please feel free to ask any questions you want.
Last edited on
@guatemala007

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?

Andy
@Andy

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.
Topic archived. No new replies allowed.