stack error

this code shows this error : stack around the variable 'Q_Rand' was corrupted
can someone tell me what is the problem?
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
// randomno.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<ctime>

using namespace std;

int main()
{
	int j=0,min=1, max=35,Q_Rand[120]={0},Q_FRand[120]={0};
	//Q_Rand[0] = 0;
	srand(time(NULL));
	for(int i=1; i<=120; i++)
	{
		Q_Rand[i] = (rand()%(max-min + 1)) + min;
		Q_FRand[i]=Q_Rand[i];
		//cout << Q_Rand <<endl ;
		for( j=0; j<i ;j++)
		{
			//cout << j << endl;
			if(Q_Rand[i]==Q_Rand[j])
				Q_FRand[i]=(rand()%(max-min + 1)) + min;
			else
				continue;
		}
	}
	for(int i=1; i<=200; i++)
	{
		cout << Q_FRand[i] <<endl;
	}
	return 0;
}



Do you think your i should start from one?

try this:
for(int i=0; i<120; i++)

Last edited on
Also notice the omission of the equal sign in mutexe's correction. This is important because it is what actually stops you from over running your array.

Depending on your skill level, you may want to also check out the range based for-loops implemented in C++-x11. You should get the basics like this down first but after that, this is a useful tool to save yourself some typing: http://en.cppreference.com/w/cpp/language/range-for
Last edited on
actually i want to generate distinct random numbers every time say between 1 to 30.
but it actually is not doing the same....so i am trying to replace the redundant nos by another random no...also i do not want to start the i from 0 because there is no use of that number it is just to make sure that j does not take a negative value that is -1 which it can take up according to this program.
i want to store all the random numbers and then i want to use the array for displaying random questions based on the numbers stored that is why i am not starting with 0.

and yes it worked when i removed the equal sign but can u tell me why?
Arrays in the C family of code ALL start at 0 not 1, so zero is the first accessible element.
it worked when i removed the equal sign but can u tell me why?

You allocated 120 elements in your array. Those elements are numbered [0] to [119]. If you attempt to reference [120], you're referencing an element that is out of bounds.

BTW, your line 29 will also index past the end of the array.

oh shit!! i got it...when u have deadlines..ur brain shits...
and yes i corrected line 29 also...
Topic archived. No new replies allowed.