Segmentation fault

Jul 18, 2011 at 4:14pm
Hi,

I know this problem is easy, but I can't figure it out by myself. I'm trying to generate 100 random numbers and then plot a histogram. For some reason, when I'm trying to run it, my Linux terminal only gives me a "Segmentation error" message.

Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
int j, k;
int index = 10;
int random_integer[index];
double number[index];
int bin[j];
for (j=0; j<10; j++)
	{bin[j]=0;}
std::cout.precision(4);
std::cout.width(4);
for(int index=0; index<10; index++) {
	random_integer[index] = (rand()%100) + 1;
	number[index] = random_integer[index] / 1000;
	cout << random_integer << number << endl;}     // generate 100 random numbers
	for (j=0; j<10; j++)                     
	{ if ((random_integer[j] >= 0.1*j) && (random_integer[j] < 0.1*j+0.1) ) {bin[j]++;}
	};                                            // put numbers into bins, by their values
for (j=0; j<10; j++)
{cout << j*0.1 << "-" << 0.1*j+0.09 << ": " << bin[j] <<"\n"; 
	

By any chance, do you know how to fix it? Or, in general, how to solve segfaults? Thank you very much in advance!
Last edited on Jul 18, 2011 at 6:17pm
Jul 18, 2011 at 4:22pm
closed account (9wX36Up4)
please write the in [code]
Jul 18, 2011 at 4:27pm
Sorry about that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 srand((unsigned)time(0));
int j, k, index;
int random_integer[index];
double number[index];
int bin[j];
std::cout.precision(4);
std::cout.width(4);
for(int index=0; index<100; index++) {
	random_integer[index] = (rand()%1000) + 1;
	number[index] = random_integer[index] / 1000;
	cout << random_integer << number << endl;     // generate 100 random numbers
	for (j=0; j<100; j++)                     
	{ if ((random_integer[j] >= 0.01*j) && (random_integer[j] < 0.01*j+0.01) ) {bin[j]++;}
	};                                            // put numbers into bins, by their values
for (j=0; j<100; j++)
{cout << j*0.01 << "-" << 0.01*j+0.009 << ": "; 
	for (k=0; k<bin[j]; k++) {cout << "*"; }
	cout << "\n";                                // create a histogram from *s
		
cin.get();}
Jul 18, 2011 at 6:02pm
1
2
int j, k, index;
int random_integer[index];
That shouldn't compile. ¿what is the size of the array?

Also, integer division returns an integer
Last edited on Jul 18, 2011 at 6:04pm
Jul 18, 2011 at 6:24pm
Thank you, ne555!
I realized I should declare the size of the array, so I declared it as 10; I also fixed the integer division, but I'm still getting a segmentation error message when trying to run the program compiled...
Topic archived. No new replies allowed.