Random number generator function issue?

Apr 10, 2012 at 3:06am
This is the program I have for a random number generator.
somehow, it does not work and the console output screen hangs.
Anything missing here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main (){
  int *data;
  srand ( time(NULL) );
  for( int i=0; i<100;i++) {
 data[i] = rand();
cout<<data[i]<<endl;
}
  return 0;
}
Apr 10, 2012 at 3:16am
You're treating data as if it was a pointer to an element of an array, but it isn't. It's just an uninitialized pointer, and accessing it is an error.

If you just want to output your values, don't store them unnecessarily:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main ()
{
    srand ( time(NULL) );
    for( int i=0; i<100;i++)
        cout << rand() << '\n';
}

If you do need to store them, use a vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;

int main ()
{
  vector<int> data(100);
  srand ( time(NULL) );
  for( size_t i=0; i<data.size(); i++)
  {
      data[i] = rand();
      cout << data[i] << '\n';
  }
}
Apr 12, 2012 at 1:56pm
thanks it worked :)
Topic archived. No new replies allowed.