RANDOM NUMBER Generator

Hi,
I am trying to generate an array of n random numbers. The following program runs fine for n<5. But when n equals or greater than 5, the code gives me Segmentation fault. Please, help me figure out whats wrong with code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* Generate an array of n random numbers */
#include <iostream>
#include <ctime> 
#include <cstdlib>

using namespace std;

int main ()
{ 
	int n, A[n];
	srand ((unsigned)time(0)); 
	cout << "Enter the size of array for random numbers: ";
	cin >> n;	 
	
	for (int i=0; i<n; i++){
	A[i]=(rand() % 1000) +1;
	cout << A[i] << " "; 
	} 

	cout << endl;
	return 0;
}


Thanks!
int n, A[n];

You can't do this.

Arrays cannot be variable size.

Especially since you didn't even give 'n' a value yet!

Use a vector instead:

1
2
3
4
5
6
7
8
9
10
int n;
vector<int> A;

//...
cin >> n;
A.resize(n);

for(int i = 0; i < n; ++i)
{
  A[i] = //... 
It worked. Thank you!!
Topic archived. No new replies allowed.