How can I fill an array correctly using rand() ? (I have errors)

Here is the piece of code that breaks the program:

1
2
3
4
5
6
void SortData::randomize(int seed)
{
	srand(seed);
	for(int i=0; i<maxSize; i++)
	theData[i] = rand();
}


Specifically, in debug mode,
theData[i] = rand();
makes the program stop working and the error reads:
"Unhandled exception at 0x00ed2a8e in ... : 0xC0000005: Access violation writing location 0xcccccccc."

The purpose of this block of code is to fill an array of maxSize with random integers, so that I can test out my sorting algorithms (and their efficiency) ont hat data. maxSize is already assigned by the time this is called (it was 10 the first time I ran this, though I will begenerating arrays with up to 1,000,000 items later on).
You can't put an int sitting in your srand declaration... see this page, and perhaps google how to use srand and rand();

http://www.cprogramming.com/fod/srand.html
Thank you for your reply. What do you mean "int sitting"?
You can't put an int sitting in your srand declaration...


Sure he can, although unsigned int might be more appropriate as that's the type the function expects.

0xcccccccc is the bit pattern VC++ uses for uninitialized variables. is theData pointing to a valid memory location?
That is a good question. Here is the code I used to create the array:

1
2
3
4
5
SortData::SortData(int max) 
{
	long *theData = new long[max];
	maxSize = max;
}


The array "theData" is a protected member of my class. The function call in the main program is something like:

BubbleSort bs10(10);

which should call the constructor for the BubbleSort class to create an instance called bs10 that uses this (inherited from the SortData constructor above) to initialize theData:

BubbleSort:: BubbleSort(int max) : SortData(max) {}
You have an actual member in SortData named theData.

Unfortunately in your constructor you declare a local variable of the same name, which hides the variable you really want to assign to.

You should change it to:
1
2
3
SortData::SortData(int max) : theData(new long[max]), maxSize(max)
{
}
Last edited on
Thank you very much for all of your help cire! I hope that someday I can be as helpful haha.
Topic archived. No new replies allowed.